AddressSanitizer.cpp revision 3780ad8b998d93d7db406919c06137cdb786ef05
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
18b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany#include "BlackList.h"
1906cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Function.h"
2006cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IRBuilder.h"
21f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany#include "llvm/InlineAsm.h"
2206cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IntrinsicInst.h"
2306cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/LLVMContext.h"
2406cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Module.h"
2506cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Type.h"
26800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.h"
27800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/OwningPtr.h"
28800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallSet.h"
29800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallString.h"
30800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallVector.h"
31800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/StringExtras.h"
3206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov#include "llvm/ADT/Triple.h"
33800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
34800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
35800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
36800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
37800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
38800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetData.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetMachine.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Instrumentation.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
44800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <string>
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
46800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
47800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
48800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
49800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
5206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanovstatic const uint64_t kDefaultShadowOffsetAndroid = 0;
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
55800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
58800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanModuleCtorName = "asan.module_ctor";
597bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanModuleDtorName = "asan.module_dtor";
607bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const int   kAsanCtorAndCtorPriority = 1;
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanReportErrorTemplate = "__asan_report_";
62800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanRegisterGlobalsName = "__asan_register_globals";
637bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
659b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
66800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanInitName = "__asan_init";
6795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryanystatic const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
68800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingOffsetName = "__asan_mapping_offset";
69800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingScaleName = "__asan_mapping_scale";
70800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackMallocName = "__asan_stack_malloc";
71800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackFreeName = "__asan_stack_free";
72800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
73800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
74800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
75800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
76800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
77800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
78c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
79c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic const size_t kNumberOfAccessSizes = 5;
80c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
81800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
82800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
83800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
84800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
85800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
86800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
87800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
88e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
89e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
90e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
916e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryanystatic cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
926e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::desc("use instrumentation with slow path for all accesses"),
936e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::Hidden, cl::init(false));
94c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// This flag limits the number of instructions to be instrumented
95324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
96324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
97324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
98324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
99324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
100324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
101324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
103800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
104800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
105800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
1119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic cl::opt<bool> ClInitializers("asan-initialization-order",
1129b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -fasan-blacklist.
116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string>  ClBlackListFile("asan-blacklist",
117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("File containing the list of functions to ignore "
118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
141800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
146800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
147800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
148800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
149800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
152c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany/// An object of this type is created while instrumenting every function.
153c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystruct AsanFunctionContext {
15411c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  AsanFunctionContext(Function &Function) : F(Function) { }
155c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
1562735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Function &F;
157c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany};
158c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
160800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystruct AddressSanitizer : public ModulePass {
161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AddressSanitizer();
16225878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  virtual const char *getPassName() const;
163c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
164c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentAddress(AsanFunctionContext &AFC,
165c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                         Instruction *OrigIns, IRBuilder<> &IRB,
166800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite);
167c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
168c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
169ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
1702735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex);
171c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
172c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
173c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Instruction *OrigIns, Value *Addr,
174c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool handleFunction(Module &M, Function &F);
1789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void createInitializerPoisonCalls(Module &M,
1799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                    Value *FirstAddr, Value *LastAddr);
180a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
181800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool poisonStackInFunction(Module &M, Function &F);
182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  virtual bool runOnModule(Module &M);
183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool insertGlobalRedzones(Module &M);
184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
186800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = AI->getAllocatedType();
189d8313be41031e4d768f5b38199904d4debff88cdEvgeniy Stepanov    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return SizeInBytes;
191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedSize(uint64_t SizeInBytes) {
193800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return ((SizeInBytes + RedzoneSize - 1)
194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            / RedzoneSize) * RedzoneSize;
195800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
196800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
197800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
198800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return getAlignedSize(SizeInBytes);
199800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
200800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
20155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *checkInterfaceFunction(Constant *FuncOrBitcast);
2029b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                   Value *ShadowBase, bool DoPoison);
2055a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
2069b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void FindDynamicInitializers(Module &M);
2079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  bool HasDynamicInitializer(GlobalVariable *G);
208800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
209800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
210800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TargetData *TD;
211800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t MappingOffset;
212800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int MappingScale;
213800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t RedzoneSize;
214800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
215800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
216800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrPtrTy;
217800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
218800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
219800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *CtorInsertBefore;
220b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany  OwningPtr<BlackList> BL;
2219db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
2229db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
223f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  InlineAsm *EmptyAsm;
2249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  SmallSet<GlobalValue*, 32> DynamicallyInitializedGlobals;
225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
226c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
227800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
228800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
229800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
230800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
231800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
232800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
233800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyAddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
234800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyModulePass *llvm::createAddressSanitizerPass() {
235800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new AddressSanitizer();
236800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
237800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
23825878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenkoconst char *AddressSanitizer::getPassName() const {
23925878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  return "AddressSanitizer";
24025878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
24125878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
2422735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
2432735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  size_t Res = CountTrailingZeros_32(TypeSize / 8);
2442735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
2452735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
2462735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
2472735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
25018c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
251800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new GlobalVariable(M, StrConst->getType(), true,
252800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst, "");
253800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
254800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
255800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Split the basic block and insert an if-then code.
256800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Before:
257800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
25856139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//   Cmp
259800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
260800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// After:
261800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
262800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   if (Cmp)
26356139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//     ThenBlock
264800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
265800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
266ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany// ThenBlock block is created and its terminator is returned.
267ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany// If Unreachable, ThenBlock is terminated with UnreachableInst, otherwise
268ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany// it is terminated with BranchInst to Tail.
269ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryanystatic TerminatorInst *splitBlockAndInsertIfThen(Value *Cmp, bool Unreachable) {
27056139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany  Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
271800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *Head = SplitBefore->getParent();
272349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
273800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TerminatorInst *HeadOldTerm = Head->getTerminator();
274ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  LLVMContext &C = Head->getParent()->getParent()->getContext();
275ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
276ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CheckTerm;
277ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  if (Unreachable)
278ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CheckTerm = new UnreachableInst(C, ThenBlock);
279ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  else
280c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    CheckTerm = BranchInst::Create(Tail, ThenBlock);
281349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BranchInst *HeadNewTerm =
282349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
283349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
284349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  return CheckTerm;
285800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
286800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
287800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
288800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
289800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Shadow = IRB.CreateLShr(Shadow, MappingScale);
290800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (MappingOffset == 0)
291800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
292800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
294800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               MappingOffset));
295800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
296800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
297c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
298c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    AsanFunctionContext &AFC, Instruction *OrigIns,
299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
300800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
301800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
302800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
303c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
305800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
306800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
307800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
308800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *SizeMinusOne = IRB.CreateSub(
309800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Size, ConstantInt::get(Size->getType(), 1));
310800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
311800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
312800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
313c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
314800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
317800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
318c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
319c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                              MemIntrinsic *MI) {
320800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
321800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
3222735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
323800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
324800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
326800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
328800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
329800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
330800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
331800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
332800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
333800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
33456139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
335ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    InsertBefore = splitBlockAndInsertIfThen(Cmp, false);
336800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
337800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
338c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
339800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
340c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
341800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
342800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
343800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
344e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
345e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
346e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
347800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
348e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
349e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
350800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
351800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
352e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
353e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
354e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
355e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
356e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
357e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
358e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
359e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
360e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
361e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
362e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
363e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
364e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
365e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
366e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
367e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
368800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
369800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
3709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanyvoid AddressSanitizer::FindDynamicInitializers(Module& M) {
3719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Clang generates metadata identifying all dynamically initialized globals.
3729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  NamedMDNode *DynamicGlobals =
3739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
3749b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!DynamicGlobals)
3759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return;
3769b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
3779b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    MDNode *MDN = DynamicGlobals->getOperand(i);
3789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    assert(MDN->getNumOperands() == 1);
3799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    Value *VG = MDN->getOperand(0);
3809b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // The optimizer may optimize away a global entirely, in which case we
3819b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // cannot instrument access to it.
3829b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (!VG)
3839b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      continue;
3849b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
3859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    GlobalVariable *G = cast<GlobalVariable>(VG);
3869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    DynamicallyInitializedGlobals.insert(G);
3879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
3889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
3899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany// Returns true if a global variable is initialized dynamically in this TU.
3909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanybool AddressSanitizer::HasDynamicInitializer(GlobalVariable *G) {
3919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  return DynamicallyInitializedGlobals.count(G);
3929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
3939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
394c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
3953780ad8b998d93d7db406919c06137cdb786ef05Axel Naumann  bool IsWrite = false;
396e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
397e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
3989b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClOpt && ClOptGlobals) {
3999b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
4009b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If initialization order checking is disabled, a simple access to a
4019b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // dynamically initialized global is always valid.
4029b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      if (!ClInitializers)
4039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
4049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If a global variable does not have dynamic initialization we don't
4059b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // have to instrument it.  However, if a global has external linkage, we
4069b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // assume it has dynamic initialization, as it may have an initializer
4079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // in a different TU.
4089b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
4099b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany          !HasDynamicInitializer(G))
4109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
4119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
412800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
4139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
414800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
415800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
416800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
417800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
418800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
419800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
420800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize != 8  && TypeSize != 16 &&
421800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
422800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all unusual sizes.
423800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
424800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
425800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
426800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
427c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
428800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
429800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
43055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
43155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
43255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
43355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
43455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander PotapenkoFunction *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
43555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
43655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
43755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
43855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
43955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
44055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
441800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
442ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    Instruction *InsertBefore, Value *Addr,
4434f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex) {
444ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  IRBuilder<> IRB(InsertBefore);
445ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
446ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany                                  Addr);
447f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
448f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
449f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
450f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
4513c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
452800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
453800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4542735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
455c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
456c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
457c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  size_t Granularity = 1 << MappingScale;
458c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
459c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
460c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
461c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
462c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
463c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
464c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
465c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
466c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
4676e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany      LastAccessedByte, ShadowValue->getType(), false);
468c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
469c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
470c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
471c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
472c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
473c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                         Instruction *OrigIns,
474800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
475800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
476800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
477800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
478800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
479800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale));
480800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
481800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
482800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
483800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
484800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
485800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
486800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
48711c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
488800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t Granularity = 1 << MappingScale;
489ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CrashTerm = 0;
490ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
4916e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
492ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    TerminatorInst *CheckTerm = splitBlockAndInsertIfThen(Cmp, false);
493ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
494f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
495c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
496c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
497ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    BasicBlock *CrashBlock = BasicBlock::Create(*C, "", &AFC.F, NextBB);
498ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = new UnreachableInst(*C, CrashBlock);
499f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
500f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
501c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
502ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = splitBlockAndInsertIfThen(Cmp, true);
503800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
504ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
505ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *Crash =
506ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany      generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
507ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
508800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
509800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanyvoid AddressSanitizer::createInitializerPoisonCalls(Module &M,
5119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                                    Value *FirstAddr,
5129b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                                    Value *LastAddr) {
5139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
5149b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
5159b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // If that function is not present, this TU contains no globals, or they have
5169b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // all been optimized away
5179b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!GlobalInit)
5189b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return;
5199b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5209b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Set up the arguments to our poison/unpoison functions.
5219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
5229b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5239b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Declare our poisoning and unpoisoning functions.
5249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
5259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
5269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
5279b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
5289b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
5299b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
5309b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add a call to poison all external globals before the given function starts.
5329b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
5339b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add calls to unpoison all globals before each return instruction.
5359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
5369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      I != E; ++I) {
5379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
5389b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      CallInst::Create(AsanUnpoisonGlobals, "", RI);
5399b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
5409b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
5419b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
5429b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5439b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanybool AddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
5449b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Type *Ty = cast<PointerType>(G->getType())->getElementType();
5459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  DEBUG(dbgs() << "GLOBAL: " << *G);
5469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
54759a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany  if (BL->isIn(*G)) return false;
5489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!Ty->isSized()) return false;
5499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!G->hasInitializer()) return false;
5509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Touch only those globals that will not be defined in other modules.
5519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Don't handle ODR type linkages since other modules may be built w/o asan.
5529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
5539b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::PrivateLinkage &&
5549b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::InternalLinkage)
5559b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
5569b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Two problems with thread-locals:
5579b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - The address of the main thread's copy can't be computed at link-time.
5589b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - Need to poison all copies, not just the main thread's one.
5599b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->isThreadLocal())
5609b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
5619b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // For now, just ignore this Alloca if the alignment is large.
5629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getAlignment() > RedzoneSize) return false;
5639b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Ignore all the globals with the names starting with "\01L_OBJC_".
5659b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Many of those are put into the .cstring section. The linker compresses
5669b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // that section by removing the spare \0s after the string terminator, so
5679b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // our redzones get broken.
5689b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if ((G->getName().find("\01L_OBJC_") == 0) ||
5699b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      (G->getName().find("\01l_OBJC_") == 0)) {
5709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
5719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
5729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
5739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5749b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->hasSection()) {
5759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    StringRef Section(G->getSection());
5769b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
5779b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
5789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // them.
5799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if ((Section.find("__OBJC,") == 0) ||
5809b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        (Section.find("__DATA, __objc_") == 0)) {
5819b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
5829b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
5839b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
5849b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
5859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Constant CFString instances are compiled in the following way:
5869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the string buffer is emitted into
5879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     __TEXT,__cstring,cstring_literals
5889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the constant NSConstantString structure referencing that buffer
5899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     is placed into __DATA,__cfstring
5909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Therefore there's no point in placing redzones into __DATA,__cfstring.
5919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Moreover, it causes the linker to crash on OS X 10.7
5929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (Section.find("__DATA,__cfstring") == 0) {
5939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring CFString: " << *G);
5949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
5959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
5969b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
5979b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5989b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  return true;
5999b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
6009b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
603800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
604800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::insertGlobalRedzones(Module &M) {
605800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
606800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Module::GlobalListType::iterator G = M.global_begin(),
6089b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       E = M.global_end(); G != E; ++G) {
6099b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ShouldInstrumentGlobal(G))
6109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      GlobalsToChange.push_back(G);
611800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
612800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
613800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
614800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
615800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
616800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
617800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
618800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
619800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
620800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
6219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   size_t has_dynamic_init;
622800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
623800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
6249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, IntptrTy,
6259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, NULL);
6269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  SmallVector<Constant *, 16> Initializers(n), DynamicInit;
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
628800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
629800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6309b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClInitializers)
6319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    FindDynamicInitializers(M);
6329b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6339b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // The addresses of the first and last dynamically initialized globals in
6349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // this TU.  Used in initialization order checking.
6359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Value *FirstDynamic = 0, *LastDynamic = 0;
6369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
637800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
638800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
640800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
641208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
642800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t RightRedzoneSize = RedzoneSize +
643800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (RedzoneSize - (SizeInBytes % RedzoneSize));
644800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
6459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Determine whether this global should be poisoned in initialization.
6469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    bool GlobalHasDynamicInitializer = HasDynamicInitializer(G);
64759a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany    // Don't check initialization order if this global is blacklisted.
6487dadac65d375ff21b7a36bfb7642578d2f467525Kostya Serebryany    GlobalHasDynamicInitializer &= !BL->isInInit(*G);
649800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
650800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
651800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
652800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
653800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
654800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
655a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
656a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
657a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
658a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
659a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
660800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
661800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
662800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
663800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
664ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
665800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
666800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->setAlignment(RedzoneSize);
667800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
668800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
669800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
670800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
671800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
672800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
673f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
674800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
675800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
676800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
677800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
678800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
679800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
680800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
681800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
682800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
6839b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
684800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
6859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Populate the first and last globals declared in this TU.
6879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ClInitializers && GlobalHasDynamicInitializer) {
6889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
6899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      if (FirstDynamic == 0)
6909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        FirstDynamic = LastDynamic;
6919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
6929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
693800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
694800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
695800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
696800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
697800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
698800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
699800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
700800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7019b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Create calls for poisoning before initializers run and unpoisoning after.
7029b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClInitializers && FirstDynamic && LastDynamic)
7039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
7049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
70555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
7069b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      kAsanRegisterGlobalsName, IRB.getVoidTy(),
7079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      IntptrTy, IntptrTy, NULL));
708800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
709800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
710800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
711800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
712800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
713800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7147bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
7157bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
7167bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
7177bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
7187bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
7197bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
7207bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
72155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanUnregisterGlobals =
72255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko      checkInterfaceFunction(M.getOrInsertFunction(
72355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          kAsanUnregisterGlobalsName,
72455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
7257bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
7267bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
7277bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
7287bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
7297bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
7307bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
7317bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
732800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
733800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
734800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
735800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
736800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// virtual
737800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::runOnModule(Module &M) {
738800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Initialize the private fields. No one has accessed them before.
739800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TD = getAnalysisIfAvailable<TargetData>();
740800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!TD)
741800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
742b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany  BL.reset(new BlackList(ClBlackListFile));
743800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
744800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  C = &(M.getContext());
745800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LongSize = TD->getPointerSizeInBits();
746800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
747800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrPtrTy = PointerType::get(IntptrTy, 0);
748800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
749800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanCtorFunction = Function::Create(
750800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
751800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
752800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
753800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
754800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
755800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // call __asan_init in the module ctor.
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
75755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  AsanInitFunction = checkInterfaceFunction(
758800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
760800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall(AsanInitFunction);
761800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7629db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
7639db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
7649db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
7659db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
7669db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
7679db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
7689db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
7694f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
77011c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
7714f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany          M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
7729db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
7739db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
774f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
775f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
776f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
777f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
7789db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
77906fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  llvm::Triple targetTriple(M.getTargetTriple());
78043bf70986bb13c812e87ca959dd8f2dd9edf802cLogan Chien  bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
78106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov
78206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
78306fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov    (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
784800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingOffsetLog >= 0) {
785800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClMappingOffsetLog == 0) {
786800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // special case
787800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 0;
788800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
789800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 1ULL << ClMappingOffsetLog;
790800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
791800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
792800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MappingScale = kDefaultShadowScale;
793800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingScale) {
794800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    MappingScale = ClMappingScale;
795800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
796800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
797800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
798800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  RedzoneSize = std::max(32, (int)(1 << MappingScale));
799800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
800800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool Res = false;
801800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
802800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClGlobals)
803800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= insertGlobalRedzones(M);
804800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8058c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingOffsetLog >= 0) {
8068c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Tell the run-time the current values of mapping offset and scale.
8078c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_offset =
8088c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
8098c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       ConstantInt::get(IntptrTy, MappingOffset),
8108c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       kAsanMappingOffsetName);
8118c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
8128c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_offset, true);
8138c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
8148c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingScale) {
8158c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_scale =
8168c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
8178c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           ConstantInt::get(IntptrTy, MappingScale),
8188c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           kAsanMappingScaleName);
8198c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
8208c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_scale, true);
8218c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
822800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
823800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
824800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
825800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (F->isDeclaration()) continue;
826800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= handleFunction(M, *F);
827800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
828800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8297bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
8309b02741d2284d9516a59666c211fe1f57e8803adKostya Serebryany
831800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return Res;
832800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
833800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
834a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
835a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
836a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
837a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
838a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
839a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
840a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
841a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
842a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
843a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
844a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
845a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
846a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
847a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
848a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
849a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
850800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::handleFunction(Module &M, Function &F) {
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
853a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
854a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // If needed, insert __asan_init before checking for AddressSafety attr.
855a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
856a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
8570307b9a88574d7e54459181afaa656ac92971847Kostya Serebryany  if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
858800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
859800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
860800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
861800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We want to instrument every address only once per basic block
862800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (unless there are calls between uses).
863800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
864800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
86595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
866e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
868800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
869800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
870800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
871800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
872324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
873800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
875bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
876e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
877800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
878800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
879800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
880800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
881800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
882800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
883800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
88495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany        if (CallInst *CI = dyn_cast<CallInst>(BI)) {
885800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
886800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
88795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          if (CI->doesNotReturn()) {
88895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany            NoReturnCalls.push_back(CI);
88995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          }
890800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
893800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
894324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
895324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
896324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
897800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
898800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
899800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9002735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  AsanFunctionContext AFC(F);
901c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
902800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
903800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
904800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
905800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
906800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
907800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
908e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
909c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        instrumentMop(AFC, Inst);
910800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
911c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
912800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
913800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
915800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
916800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << F);
917800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
918800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool ChangedStack = poisonStackInFunction(M, F);
91995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
92095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
92195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
92295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
92395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
92495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
92595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
92695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany                                         IRB.getVoidTy(), NULL));
92795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
92895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
92995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
934800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
936800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
937800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
938858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
939800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
940800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
941800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
942800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
943800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t RedzoneSize,
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < RedzoneSize;
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
949800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
950800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
957800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   IRBuilder<> IRB,
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Value *ShadowBase, bool DoPoison) {
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t ShadowRZSize = RedzoneSize >> MappingScale;
962800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
964800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
981800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize);
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
987800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
988800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
989800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
990800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
992800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                       (Pos >> MappingScale) - ShadowRZSize));
993800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        RedzoneSize,
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        1ULL << MappingScale,
999800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1003800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1004800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1005800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
1006800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
1007800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale));
1008800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1010800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1011800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += RedzoneSize;
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1013800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1014800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10155a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// Workaround for bug 11395: we don't want to instrument stack in functions
10165a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1017d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany// FIXME: remove once the bug 11395 is fixed.
10185a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryanybool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
10195a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (LongSize != 32) return false;
10205a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  CallInst *CI = dyn_cast<CallInst>(I);
10215a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (!CI || !CI->isInlineAsm()) return false;
10225a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (CI->getNumArgOperands() <= 5) return false;
10235a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  // We have inline assembly with quite a few arguments.
10245a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  return true;
10255a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany}
10265a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany
1027800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Find all static Alloca instructions and put
1028800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// poisoned red zones around all of them.
1029800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Then unpoison everything back before the function returns.
1030800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
1031800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Stack poisoning does not play well with exception handling.
1032800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// When an exception is thrown, we essentially bypass the code
1033800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// that unpoisones the stack. This is why the run-time library has
1034800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// stack in the interceptor. This however does not work inside the
1036800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// actual function which catches the exception. Most likely because the
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// compiler hoists the load of the shadow value somewhere too high.
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This causes asan to report a non-existing bug on 453.povray.
1039800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// It sounds like an LLVM bug.
1040800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
1041800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClStack) return false;
1042800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<AllocaInst*, 16> AllocaVec;
1043800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 8> RetVec;
1044800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t TotalSize = 0;
1045800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1046800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Filter out Alloca instructions we want (and can) handle.
1047800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Collect Ret instructions.
1048800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
1049800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
1050800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    BasicBlock &BB = *FI;
1051800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1052800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
1053800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (isa<ReturnInst>(BI)) {
1054800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          RetVec.push_back(BI);
1055800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          continue;
1056800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1057800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1058800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1059800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI) continue;
1060800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->isArrayAllocation()) continue;
1061800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->isStaticAlloca()) continue;
1062800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->getAllocatedType()->isSized()) continue;
1063800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->getAlignment() > RedzoneSize) continue;
1064800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaVec.push_back(AI);
1065800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint64_t AlignedSize =  getAlignedAllocaSize(AI);
1066800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TotalSize += AlignedSize;
1067800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1068800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1069800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1070800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (AllocaVec.empty()) return false;
1071800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1072800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1073800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1074800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool DoStackMalloc = ClUseAfterReturn
1075800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
1076800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1077800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
1078800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
1079800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1080800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1081800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1082800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
1083800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1084800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MyAlloca->setAlignment(RedzoneSize);
1085800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
1086800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1087800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
1088800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1089800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1090800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AsanStackMallocFunc = M.getOrInsertFunction(
1091800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
1092800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1093800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1094800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1095800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1096800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
1097800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
1098800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
1099800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1100800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1101800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
1102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
1103800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1104800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1105800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
1107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
1108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
1109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert((AlignedSize % RedzoneSize) == 0);
1111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AI->replaceAllUsesWith(
1112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IRB.CreateIntToPtr(
1113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            AI->getType()));
1115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize + RedzoneSize;
1116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
1120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
1123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   ConstantInt::get(IntptrTy, LongSize/8));
1125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Description = IRB.CreatePointerCast(
1127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      createPrivateGlobalForString(M, StackDescription.str()),
1128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IntptrTy);
1129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
1130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
1132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AsanStackFreeFunc = NULL;
1136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AsanStackFreeFunc = M.getOrInsertFunction(
1138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackFreeName, IRB.getVoidTy(),
1139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IntptrTy, IntptrTy, IntptrTy, NULL);
1140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1141800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1146800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1147800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1148800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1149800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
1151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1153800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1154800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1155800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1156800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1160800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClDebugStack) {
1161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << F);
1162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1163800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1164800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1165800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1166