AddressSanitizer.cpp revision 407790604b8f71f7172bbdfb76c27e1799d241c2
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"
383574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow#include "llvm/DataLayout.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 {
151ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany/// A set of dynamically initialized globals extracted from metadata.
152ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryanyclass SetOfDynamicallyInitializedGlobals {
153ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany public:
154ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  void Init(Module& M) {
155ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    // Clang generates metadata identifying all dynamically initialized globals.
156ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    NamedMDNode *DynamicGlobals =
157ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
158ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    if (!DynamicGlobals)
159ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      return;
160ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
161ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      MDNode *MDN = DynamicGlobals->getOperand(i);
162ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      assert(MDN->getNumOperands() == 1);
163ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      Value *VG = MDN->getOperand(0);
164ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // The optimizer may optimize away a global entirely, in which case we
165ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // cannot instrument access to it.
166ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      if (!VG)
167ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        continue;
168ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      DynInitGlobals.insert(cast<GlobalVariable>(VG));
169ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    }
170ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  }
171ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
172ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany private:
173ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SmallSet<GlobalValue*, 32> DynInitGlobals;
174ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany};
175ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
176ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
178ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanystruct AddressSanitizer : public FunctionPass {
179800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AddressSanitizer();
18025878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  virtual const char *getPassName() const;
181ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMop(Instruction *I);
182ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite);
184c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
185c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
186ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
1872735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex);
188ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool instrumentMemIntrinsic(MemIntrinsic *MI);
189ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
190c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
193ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool runOnFunction(Function &F);
1949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void createInitializerPoisonCalls(Module &M,
1959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                    Value *FirstAddr, Value *LastAddr);
196a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
197ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool poisonStackInFunction(Function &F);
198ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  virtual bool doInitialization(Module &M);
199ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  virtual bool doFinalization(Module &M);
200800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool insertGlobalRedzones(Module &M);
201800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
202800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
205800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = AI->getAllocatedType();
206d8313be41031e4d768f5b38199904d4debff88cdEvgeniy Stepanov    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
207800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return SizeInBytes;
208800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
209800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedSize(uint64_t SizeInBytes) {
210800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return ((SizeInBytes + RedzoneSize - 1)
211800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            / RedzoneSize) * RedzoneSize;
212800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
213800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
214800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
215800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return getAlignedSize(SizeInBytes);
216800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
217800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
21855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *checkInterfaceFunction(Constant *FuncOrBitcast);
2199b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
220800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
221800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                   Value *ShadowBase, bool DoPoison);
2225a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
2239b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void FindDynamicInitializers(Module &M);
224800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
2263574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  DataLayout *TD;
227800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t MappingOffset;
228800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int MappingScale;
229800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t RedzoneSize;
230800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
231800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
232800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrPtrTy;
233800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
234800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
235ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  Function *AsanStackMallocFunc, *AsanStackFreeFunc;
236ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  Function *AsanHandleNoReturnFunc;
237800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *CtorInsertBefore;
238b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany  OwningPtr<BlackList> BL;
2399db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
2409db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
241f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  InlineAsm *EmptyAsm;
242a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany  SmallSet<GlobalValue*, 32> GlobalsCreatedByAsan;
243ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
245c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
246800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
250800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
251800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
252ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya SerebryanyAddressSanitizer::AddressSanitizer() : FunctionPass(ID) { }
253ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya SerebryanyFunctionPass *llvm::createAddressSanitizerPass() {
254800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new AddressSanitizer();
255800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
256800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
25725878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenkoconst char *AddressSanitizer::getPassName() const {
25825878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  return "AddressSanitizer";
25925878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
26025878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
2612735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
2622735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  size_t Res = CountTrailingZeros_32(TypeSize / 8);
2632735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
2642735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
2652735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
2662735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
267800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
268800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
26918c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
270800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new GlobalVariable(M, StrConst->getType(), true,
271800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst, "");
272800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
273800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
274800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
275800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
276800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Shadow = IRB.CreateLShr(Shadow, MappingScale);
277800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (MappingOffset == 0)
278800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
279800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
280800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
281800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               MappingOffset));
282800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
283800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
284c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
285ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    Instruction *OrigIns,
286800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
287800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
288800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
289800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
290ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
291800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
292800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
294800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
295800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *SizeMinusOne = IRB.CreateSub(
296800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Size, ConstantInt::get(Size->getType(), 1));
297800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
298800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
300ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
301800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
302800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
303800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
305ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
306800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
307800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
3082735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
309800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
310800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
311800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
312800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
313800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
314800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
317800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
318800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
319800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
32056139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
3214a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
322800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
323800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
324ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
326ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
328800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
329800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
330e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
331e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
332e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
333800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
334e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
335e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
336800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
337800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
338e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
339e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
340e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
341e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
342e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
343e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
344e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
345e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
346e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
347e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
348e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
349e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
350e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
351e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
352e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
353e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
354800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
355800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
356ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentMop(Instruction *I) {
3573780ad8b998d93d7db406919c06137cdb786ef05Axel Naumann  bool IsWrite = false;
358e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
359e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
3609b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClOpt && ClOptGlobals) {
3619b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
3629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If initialization order checking is disabled, a simple access to a
3639b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // dynamically initialized global is always valid.
3649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      if (!ClInitializers)
3659b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
3669b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If a global variable does not have dynamic initialization we don't
367407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // have to instrument it.  However, if a global does not have initailizer
368407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // at all, we assume it has dynamic initializer (in other TU).
369407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
3709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
3719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
372800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
3739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
374800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
375800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
376800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
377800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
378800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
379800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
380800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize != 8  && TypeSize != 16 &&
381800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
382800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all unusual sizes.
383800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
384800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
385800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
386800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
387ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
388800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
389800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
39055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
39155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
39255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
39355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
39455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander PotapenkoFunction *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
39555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
39655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
39755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
39855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
39955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
40055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
401800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
402ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    Instruction *InsertBefore, Value *Addr,
4034f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex) {
404ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  IRBuilder<> IRB(InsertBefore);
405ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
406ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany                                  Addr);
407f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
408f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
409f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
410f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
4113c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
412800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
413800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4142735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
415c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
416c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
417c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  size_t Granularity = 1 << MappingScale;
418c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
419c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
420c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
421c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
422c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
423c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
424c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
425c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
426c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
4276e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany      LastAccessedByte, ShadowValue->getType(), false);
428c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
429c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
430c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
431c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
432ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(Instruction *OrigIns,
433800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
435800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
436800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
437800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
438800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale));
439800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
441800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
442800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
443800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
444800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
445800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
44611c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
447800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t Granularity = 1 << MappingScale;
448ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CrashTerm = 0;
449ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
4506e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
4514a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    TerminatorInst *CheckTerm =
4524a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
453ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
454f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
455c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
456c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
457ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    BasicBlock *CrashBlock =
458ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
459ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = new UnreachableInst(*C, CrashBlock);
460f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
461f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
462c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
4634a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
464800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
465ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
466ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *Crash =
467ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany      generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
468ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
469800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
470800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanyvoid AddressSanitizer::createInitializerPoisonCalls(Module &M,
4729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                                    Value *FirstAddr,
4739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                                    Value *LastAddr) {
4749b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
4759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
4769b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // If that function is not present, this TU contains no globals, or they have
4779b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // all been optimized away
4789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!GlobalInit)
4799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return;
4809b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
4819b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Set up the arguments to our poison/unpoison functions.
4829b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
4839b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
4849b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Declare our poisoning and unpoisoning functions.
4859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
4869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
4879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
4889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
4899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
4909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
4919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
4929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add a call to poison all external globals before the given function starts.
4939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
4949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
4959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add calls to unpoison all globals before each return instruction.
4969b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
4979b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      I != E; ++I) {
4989b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
4999b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      CallInst::Create(AsanUnpoisonGlobals, "", RI);
5009b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
5019b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
5029b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
5039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanybool AddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
5059b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Type *Ty = cast<PointerType>(G->getType())->getElementType();
506324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
5079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
50859a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany  if (BL->isIn(*G)) return false;
5099b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!Ty->isSized()) return false;
5109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!G->hasInitializer()) return false;
5119ce84c1c95c0153a2f33e188ce0db00770425f9eAlexey Samsonov  if (GlobalsCreatedByAsan.count(G)) return false;  // Our own global.
5129b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Touch only those globals that will not be defined in other modules.
5139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Don't handle ODR type linkages since other modules may be built w/o asan.
5149b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
5159b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::PrivateLinkage &&
5169b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::InternalLinkage)
5179b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
5189b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Two problems with thread-locals:
5199b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - The address of the main thread's copy can't be computed at link-time.
5209b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - Need to poison all copies, not just the main thread's one.
5219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->isThreadLocal())
5229b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
5239b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // For now, just ignore this Alloca if the alignment is large.
5249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getAlignment() > RedzoneSize) return false;
5259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Ignore all the globals with the names starting with "\01L_OBJC_".
5279b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Many of those are put into the .cstring section. The linker compresses
5289b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // that section by removing the spare \0s after the string terminator, so
5299b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // our redzones get broken.
5309b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if ((G->getName().find("\01L_OBJC_") == 0) ||
5319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      (G->getName().find("\01l_OBJC_") == 0)) {
5329b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
5339b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
5349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
5359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->hasSection()) {
5379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    StringRef Section(G->getSection());
5389b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
5399b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
5409b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // them.
5419b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if ((Section.find("__OBJC,") == 0) ||
5429b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        (Section.find("__DATA, __objc_") == 0)) {
5439b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
5449b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
5459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
5469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
5479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Constant CFString instances are compiled in the following way:
5489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the string buffer is emitted into
5499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     __TEXT,__cstring,cstring_literals
5509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the constant NSConstantString structure referencing that buffer
5519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     is placed into __DATA,__cfstring
5529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Therefore there's no point in placing redzones into __DATA,__cfstring.
5539b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Moreover, it causes the linker to crash on OS X 10.7
5549b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (Section.find("__DATA,__cfstring") == 0) {
5559b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring CFString: " << *G);
5569b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
5579b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
5589b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
5599b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
5609b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  return true;
5619b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
5629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
563800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
564800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
565800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
566800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::insertGlobalRedzones(Module &M) {
567800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
568800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5699b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Module::GlobalListType::iterator G = M.global_begin(),
5709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       E = M.global_end(); G != E; ++G) {
5719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ShouldInstrumentGlobal(G))
5729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      GlobalsToChange.push_back(G);
573800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
574800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
575800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
576800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
577800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
578800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
580800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
581800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
582800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
5839b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   size_t has_dynamic_init;
584800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
585800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
5869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, IntptrTy,
5879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, NULL);
5889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  SmallVector<Constant *, 16> Initializers(n), DynamicInit;
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
590800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
591800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // The addresses of the first and last dynamically initialized globals in
5939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // this TU.  Used in initialization order checking.
5949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Value *FirstDynamic = 0, *LastDynamic = 0;
5959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
599800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
600208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t RightRedzoneSize = RedzoneSize +
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (RedzoneSize - (SizeInBytes % RedzoneSize));
603800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
6049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Determine whether this global should be poisoned in initialization.
605ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    bool GlobalHasDynamicInitializer =
606ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        DynamicallyInitializedGlobals.Contains(G);
60759a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany    // Don't check initialization order if this global is blacklisted.
6087dadac65d375ff21b7a36bfb7642578d2f467525Kostya Serebryany    GlobalHasDynamicInitializer &= !BL->isInInit(*G);
609800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
610800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
611800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
612800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
613800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
614800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
615a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
616a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
617a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
618a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
619a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
620800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
621800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
622800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
623800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
624ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
625800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
626800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->setAlignment(RedzoneSize);
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
628800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
629800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
630800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
631800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
632800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
633f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
634800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
635800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
636800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
637800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
638800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
640800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
641800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
642800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
6439b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
644800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
6459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Populate the first and last globals declared in this TU.
6479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ClInitializers && GlobalHasDynamicInitializer) {
6489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
6499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      if (FirstDynamic == 0)
6509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        FirstDynamic = LastDynamic;
6519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
6529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
653324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
654800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
655800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
656800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
657800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
658800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
659800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
660800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6619b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Create calls for poisoning before initializers run and unpoisoning after.
6629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClInitializers && FirstDynamic && LastDynamic)
6639b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
6649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
66555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
6669b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      kAsanRegisterGlobalsName, IRB.getVoidTy(),
6679b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      IntptrTy, IntptrTy, NULL));
668800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
669800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
670800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
671800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
672800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
673800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6747bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
6757bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
6767bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
6777bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
6787bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
6797bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
6807bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
68155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanUnregisterGlobals =
68255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko      checkInterfaceFunction(M.getOrInsertFunction(
68355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          kAsanUnregisterGlobalsName,
68455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
6857bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
6867bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
6877bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
6887bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
6897bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
6907bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
6917bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
692800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
693800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
694800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
695800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
696800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// virtual
697ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::doInitialization(Module &M) {
698800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Initialize the private fields. No one has accessed them before.
6993574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  TD = getAnalysisIfAvailable<DataLayout>();
700ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
701800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!TD)
702800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
703b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany  BL.reset(new BlackList(ClBlackListFile));
704ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  DynamicallyInitializedGlobals.Init(M);
705800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
706800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  C = &(M.getContext());
707426c2bf5cdd2173e4a33aea8cb92cf684a724f4bChandler Carruth  LongSize = TD->getPointerSizeInBits();
708800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
709800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrPtrTy = PointerType::get(IntptrTy, 0);
710800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
711800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanCtorFunction = Function::Create(
712800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
713800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
714800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
715800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
716800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
717800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // call __asan_init in the module ctor.
718800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
71955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  AsanInitFunction = checkInterfaceFunction(
720800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
721800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
722800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall(AsanInitFunction);
723800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7249db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
7259db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
7269db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
7279db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
7289db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
7299db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
7309db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
7314f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
7327846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
7337846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany          checkInterfaceFunction(M.getOrInsertFunction(
7347846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany              FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
7359db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
7369db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
737ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
738ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
739ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
740ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
741ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      kAsanStackFreeName, IRB.getVoidTy(),
742ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      IntptrTy, IntptrTy, IntptrTy, NULL));
743ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
744ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
745ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
746f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
747f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
748f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
749f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
7509db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
75106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  llvm::Triple targetTriple(M.getTargetTriple());
75243bf70986bb13c812e87ca959dd8f2dd9edf802cLogan Chien  bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
75306fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov
75406fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
75506fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov    (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingOffsetLog >= 0) {
757800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClMappingOffsetLog == 0) {
758800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // special case
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 0;
760800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
761800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 1ULL << ClMappingOffsetLog;
762800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
763800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
764800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MappingScale = kDefaultShadowScale;
765800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingScale) {
766800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    MappingScale = ClMappingScale;
767800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
768800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
769800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
770800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  RedzoneSize = std::max(32, (int)(1 << MappingScale));
771800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
772800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7738c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingOffsetLog >= 0) {
7748c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Tell the run-time the current values of mapping offset and scale.
7758c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_offset =
7768c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
7778c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       ConstantInt::get(IntptrTy, MappingOffset),
7788c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       kAsanMappingOffsetName);
7798c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
7808c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_offset, true);
7818c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
7828c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingScale) {
7838c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_scale =
7848c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
7858c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           ConstantInt::get(IntptrTy, MappingScale),
7868c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           kAsanMappingScaleName);
7878c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
7888c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_scale, true);
7898c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
790800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7917bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
7929b02741d2284d9516a59666c211fe1f57e8803adKostya Serebryany
793ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  return true;
794ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany}
795ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
796ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::doFinalization(Module &M) {
797ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  // We transform the globals at the very end so that the optimization analysis
798ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  // works on the original globals.
799ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  if (ClGlobals)
800ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    return insertGlobalRedzones(M);
801ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  return false;
802800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
803800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
804ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
805a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
806a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
807a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
808a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
809a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
810a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
811a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
812a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
813a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
814a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
815a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
816a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
817a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
818a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
819a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
820a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
821ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::runOnFunction(Function &F) {
822800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
823800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
824324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
825a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
826a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // If needed, insert __asan_init before checking for AddressSafety attr.
827a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
828a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
8296765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
8306765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling    return false;
831800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
832800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
833800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
8346765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling
8356765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // We want to instrument every address only once per basic block (unless there
8366765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // are calls between uses).
837800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
838800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
83995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
840e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
841800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
842800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
843800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
844800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
845800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
846324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
847800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
848800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
849bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
850e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
853800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
854800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
855800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
856800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
857800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
85895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany        if (CallInst *CI = dyn_cast<CallInst>(BI)) {
859800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
860800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
86195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          if (CI->doesNotReturn()) {
86295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany            NoReturnCalls.push_back(CI);
86395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          }
864800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
865800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
866800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
868324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
869324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
870324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
871800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
872800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
873800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
875800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
876800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
877800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
878800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
879800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
880e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
881ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMop(Inst);
882800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
883ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
884800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
885800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
886800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
887800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
888ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool ChangedStack = poisonStackInFunction(F);
88995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
89095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
89195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
89295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
89395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
89495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
895ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    IRB.CreateCall(AsanHandleNoReturnFunc);
89695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
897324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
89895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
89995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
900800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
901800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
902800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
903800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
904800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
905800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
906800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
907800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
908858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
909800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
910800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
911800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
912800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
913800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t RedzoneSize,
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
915800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
916800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < RedzoneSize;
917800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
918800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
919800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
920800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
921800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
922800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
923800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
924800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
925800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
926800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
927800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
929800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   IRBuilder<> IRB,
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Value *ShadowBase, bool DoPoison) {
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t ShadowRZSize = RedzoneSize >> MappingScale;
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
934800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
936800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
937800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
938800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
939800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
940800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
941800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
942800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
943800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
949800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
950800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize);
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
957800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
962800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                       (Pos >> MappingScale) - ShadowRZSize));
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
964800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        RedzoneSize,
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        1ULL << MappingScale,
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale));
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
981800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += RedzoneSize;
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9855a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// Workaround for bug 11395: we don't want to instrument stack in functions
9865a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
987d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany// FIXME: remove once the bug 11395 is fixed.
9885a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryanybool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
9895a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (LongSize != 32) return false;
9905a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  CallInst *CI = dyn_cast<CallInst>(I);
9915a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (!CI || !CI->isInlineAsm()) return false;
9925a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (CI->getNumArgOperands() <= 5) return false;
9935a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  // We have inline assembly with quite a few arguments.
9945a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  return true;
9955a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany}
9965a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Find all static Alloca instructions and put
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// poisoned red zones around all of them.
999800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Then unpoison everything back before the function returns.
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Stack poisoning does not play well with exception handling.
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// When an exception is thrown, we essentially bypass the code
1003800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// that unpoisones the stack. This is why the run-time library has
1004800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1005800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// stack in the interceptor. This however does not work inside the
1006800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// actual function which catches the exception. Most likely because the
1007800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// compiler hoists the load of the shadow value somewhere too high.
1008800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This causes asan to report a non-existing bug on 453.povray.
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// It sounds like an LLVM bug.
1010ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::poisonStackInFunction(Function &F) {
1011800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClStack) return false;
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<AllocaInst*, 16> AllocaVec;
1013800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 8> RetVec;
1014800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t TotalSize = 0;
1015800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1016800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Filter out Alloca instructions we want (and can) handle.
1017800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Collect Ret instructions.
1018800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
1020800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    BasicBlock &BB = *FI;
1021800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1022800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
1023800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (isa<ReturnInst>(BI)) {
1024800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          RetVec.push_back(BI);
1025800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          continue;
1026800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1027800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1028800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1029800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI) continue;
1030800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->isArrayAllocation()) continue;
1031800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->isStaticAlloca()) continue;
1032800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->getAllocatedType()->isSized()) continue;
1033800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->getAlignment() > RedzoneSize) continue;
1034800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaVec.push_back(AI);
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint64_t AlignedSize =  getAlignedAllocaSize(AI);
1036800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TotalSize += AlignedSize;
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1039800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1040800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (AllocaVec.empty()) return false;
1041800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1042800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1043800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1044800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool DoStackMalloc = ClUseAfterReturn
1045800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
1046800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1047800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
1048800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
1049800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1050800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1051800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1052800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
1053800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1054800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MyAlloca->setAlignment(RedzoneSize);
1055800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
1056800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1057800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
1058800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1059800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1060800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1061800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1062800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1063800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1064800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
1065800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
1066800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
1067800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1068800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1069800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
1070800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
1071800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1072800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1073800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1074800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
1075800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
1076800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
1077800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1078800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert((AlignedSize % RedzoneSize) == 0);
1079800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AI->replaceAllUsesWith(
1080800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IRB.CreateIntToPtr(
1081800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1082800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            AI->getType()));
1083800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize + RedzoneSize;
1084800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1085800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1086800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1087800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
1088800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1089800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1090800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
1091800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1092800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   ConstantInt::get(IntptrTy, LongSize/8));
1093800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
10949ce84c1c95c0153a2f33e188ce0db00770425f9eAlexey Samsonov  GlobalVariable *StackDescriptionGlobal =
1095a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany      createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1096a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany  GlobalsCreatedByAsan.insert(StackDescriptionGlobal);
1097a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1098800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
1099800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1100800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
1101800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1103800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1104800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1105800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
1113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1122bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  // We are done. Remove the old unused alloca instructions.
1123bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1124bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany    AllocaVec[i]->eraseFromParent();
1125bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany
1126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClDebugStack) {
1127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << F);
1128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1132