AddressSanitizer.cpp revision ebd6454929f2ba3b92f61c151eccde0b8b0a8ded
1800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
3800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//                     The LLVM Compiler Infrastructure
4800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
5800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is distributed under the University of Illinois Open Source
6800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// License. See LICENSE.TXT for details.
7800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
8800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
9800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
10800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is a part of AddressSanitizer, an address sanity checker.
11800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Details of the algorithm:
12800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
14800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
15800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
16800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#define DEBUG_TYPE "asan"
17800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
18a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany#include "FunctionBlackList.h"
1906cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Function.h"
2006cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IRBuilder.h"
21f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany#include "llvm/InlineAsm.h"
2206cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IntrinsicInst.h"
2306cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/LLVMContext.h"
2406cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Module.h"
2506cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Type.h"
26800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.h"
27800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/OwningPtr.h"
28800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallSet.h"
29800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallString.h"
30800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallVector.h"
31800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/StringExtras.h"
3206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov#include "llvm/ADT/Triple.h"
33800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
34800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
35800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
36800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
37800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
38800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetData.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetMachine.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Instrumentation.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
44800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <string>
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
46800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
47800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
48800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
49800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
5206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanovstatic const uint64_t kDefaultShadowOffsetAndroid = 0;
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
55800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
58800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanModuleCtorName = "asan.module_ctor";
597bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanModuleDtorName = "asan.module_dtor";
607bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const int   kAsanCtorAndCtorPriority = 1;
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanReportErrorTemplate = "__asan_report_";
62800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanRegisterGlobalsName = "__asan_register_globals";
637bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
64800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanInitName = "__asan_init";
6595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryanystatic const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
66800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingOffsetName = "__asan_mapping_offset";
67800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingScaleName = "__asan_mapping_scale";
68800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackMallocName = "__asan_stack_malloc";
69800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackFreeName = "__asan_stack_free";
70800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
71800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
72800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
73800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
74800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
75800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
76c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
77c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic const size_t kNumberOfAccessSizes = 5;
78c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
79800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
80800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
81800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
82800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
83800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
84800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
85800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
86e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
87e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
88e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
89c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// This flag limits the number of instructions to be instrumented
90324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
91324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
92324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
93324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
94324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
95324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
96324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
97800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
98800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
99800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
100800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
101800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
103800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
104800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
105800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -fasan-blacklist.
109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string>  ClBlackListFile("asan-blacklist",
110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("File containing the list of functions to ignore "
111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
141800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
145c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany/// An object of this type is created while instrumenting every function.
146c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystruct AsanFunctionContext {
14711c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  AsanFunctionContext(Function &Function) : F(Function) { }
148c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
1492735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Function &F;
150c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany};
151c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
153800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystruct AddressSanitizer : public ModulePass {
154800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AddressSanitizer();
15525878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  virtual const char *getPassName() const;
156c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
157c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentAddress(AsanFunctionContext &AFC,
158c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                         Instruction *OrigIns, IRBuilder<> &IRB,
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite);
160c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
161c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
162ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
1632735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex);
164c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
165c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
166c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Instruction *OrigIns, Value *Addr,
167c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
168800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
169800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
170800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool handleFunction(Module &M, Function &F);
171a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
172800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool poisonStackInFunction(Module &M, Function &F);
173800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  virtual bool runOnModule(Module &M);
174800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool insertGlobalRedzones(Module &M);
175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
178800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
179800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
180800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = AI->getAllocatedType();
181d8313be41031e4d768f5b38199904d4debff88cdEvgeniy Stepanov    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return SizeInBytes;
183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedSize(uint64_t SizeInBytes) {
185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return ((SizeInBytes + RedzoneSize - 1)
186800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            / RedzoneSize) * RedzoneSize;
187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
189800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return getAlignedSize(SizeInBytes);
191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
19355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *checkInterfaceFunction(Constant *FuncOrBitcast);
194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
195800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                   Value *ShadowBase, bool DoPoison);
1965a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
197800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
198800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
199800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TargetData *TD;
200800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t MappingOffset;
201800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int MappingScale;
202800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t RedzoneSize;
203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
205800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrPtrTy;
206800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
207800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
208800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *CtorInsertBefore;
209a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  OwningPtr<FunctionBlackList> BL;
2109db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
2119db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
212f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  InlineAsm *EmptyAsm;
213800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
214c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
215800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
216800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
217800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
218800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
219800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
220800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
221800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyAddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
222800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyModulePass *llvm::createAddressSanitizerPass() {
223800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new AddressSanitizer();
224800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
22625878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenkoconst char *AddressSanitizer::getPassName() const {
22725878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  return "AddressSanitizer";
22825878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
22925878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
2302735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
2312735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  size_t Res = CountTrailingZeros_32(TypeSize / 8);
2322735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
2332735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
2342735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
2352735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
236800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
237800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
23818c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
239800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new GlobalVariable(M, StrConst->getType(), true,
240800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst, "");
241800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
242800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
243800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Split the basic block and insert an if-then code.
244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Before:
245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
24656139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//   Cmp
247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// After:
249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
250800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   if (Cmp)
25156139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//     ThenBlock
252800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
253800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
254ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany// ThenBlock block is created and its terminator is returned.
255ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany// If Unreachable, ThenBlock is terminated with UnreachableInst, otherwise
256ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany// it is terminated with BranchInst to Tail.
257ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryanystatic TerminatorInst *splitBlockAndInsertIfThen(Value *Cmp, bool Unreachable) {
25856139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany  Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
259800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *Head = SplitBefore->getParent();
260349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
261800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TerminatorInst *HeadOldTerm = Head->getTerminator();
262ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  LLVMContext &C = Head->getParent()->getParent()->getContext();
263ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
264ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CheckTerm;
265ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  if (Unreachable)
266ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CheckTerm = new UnreachableInst(C, ThenBlock);
267ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  else
268c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    CheckTerm = BranchInst::Create(Tail, ThenBlock);
269349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BranchInst *HeadNewTerm =
270349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
271349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
272349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  return CheckTerm;
273800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
274800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
275800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
276800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
277800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Shadow = IRB.CreateLShr(Shadow, MappingScale);
278800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (MappingOffset == 0)
279800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
280800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
281800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
282800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               MappingOffset));
283800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
284800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
285c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
286c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    AsanFunctionContext &AFC, Instruction *OrigIns,
287800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
288800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
289800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
290800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
291c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
292800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
294800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
295800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
296800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *SizeMinusOne = IRB.CreateSub(
297800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Size, ConstantInt::get(Size->getType(), 1));
298800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
300800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
301c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
302800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
303800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
305800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
306c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
307c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                              MemIntrinsic *MI) {
308800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
309800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
3102735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
311800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
312800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
313800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
314800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
317800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
318800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
319800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
320800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
321800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
32256139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
323ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    InsertBefore = splitBlockAndInsertIfThen(Cmp, false);
324800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
326c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
328c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
329800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
330800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
331800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
332e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
333e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
334e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
335800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
336e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
337e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
338800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
339800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
340e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
341e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
342e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
343e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
344e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
345e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
346e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
347e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
348e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
349e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
350e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
351e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
352e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
353e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
354e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
355e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
356800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
357800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
358c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
359e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
360e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
361e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
362800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
363800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // We are accessing a global scalar variable. Nothing to catch here.
364800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
365800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
366800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
367800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
368800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
369800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
370800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
371800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
372800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize != 8  && TypeSize != 16 &&
373800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
374800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all unusual sizes.
375800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
376800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
377800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
378800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
379c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
380800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
381800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
38255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
38355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
38455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
38555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
38655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander PotapenkoFunction *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
38755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
38855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
38955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
39055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
39155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
39255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
393800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
394ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    Instruction *InsertBefore, Value *Addr,
3954f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex) {
396ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  IRBuilder<> IRB(InsertBefore);
397ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
398ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany                                  Addr);
399f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
400f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
401f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
402f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
4033c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
404800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
405800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4062735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
407c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
408c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
409c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  size_t Granularity = 1 << MappingScale;
410c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
411c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
412c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
413c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
414c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
415c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
416c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
417c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
418c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
419c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      LastAccessedByte, IRB.getInt8Ty(), false);
420c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
421c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
422c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
423c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
424c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
425c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                         Instruction *OrigIns,
426800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
427800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
428800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
429800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
430800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
431800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale));
432800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
433800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
435800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
436800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
437800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
438800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
43911c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t Granularity = 1 << MappingScale;
441ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CrashTerm = 0;
442ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
443800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize < 8 * Granularity) {
444ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    TerminatorInst *CheckTerm = splitBlockAndInsertIfThen(Cmp, false);
445ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
446f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
447c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
448c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
449ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    BasicBlock *CrashBlock = BasicBlock::Create(*C, "", &AFC.F, NextBB);
450ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = new UnreachableInst(*C, CrashBlock);
451f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
452f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
453c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
454ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = splitBlockAndInsertIfThen(Cmp, true);
455800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
456ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
457ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *Crash =
458ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany      generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
459ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
460800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
461800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
462800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
463800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
464800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
465800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::insertGlobalRedzones(Module &M) {
466800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
467800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
468800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
469800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       E = M.getGlobalList().end(); G != E; ++G) {
470800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = cast<PointerType>(G->getType())->getElementType();
471800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "GLOBAL: " << *G);
472800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
473800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!Ty->isSized()) continue;
474800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!G->hasInitializer()) continue;
4757cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Touch only those globals that will not be defined in other modules.
4767cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Don't handle ODR type linkages since other modules may be built w/o asan.
4772e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany    if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
4782e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::PrivateLinkage &&
4792e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::InternalLinkage)
480800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
481d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    // Two problems with thread-locals:
482d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - The address of the main thread's copy can't be computed at link-time.
483d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - Need to poison all copies, not just the main thread's one.
484d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    if (G->isThreadLocal())
485d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany      continue;
486800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // For now, just ignore this Alloca if the alignment is large.
487800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->getAlignment() > RedzoneSize) continue;
488800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
489800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all the globals with the names starting with "\01L_OBJC_".
490800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Many of those are put into the .cstring section. The linker compresses
491800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // that section by removing the spare \0s after the string terminator, so
492800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // our redzones get broken.
493800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if ((G->getName().find("\01L_OBJC_") == 0) ||
494800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (G->getName().find("\01l_OBJC_") == 0)) {
495800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
496800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
497800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
498800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
499800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->hasSection()) {
500800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      StringRef Section(G->getSection());
5018375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Ignore the globals from the __OBJC section. The ObjC runtime assumes
5028375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
5038375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // them.
504800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if ((Section.find("__OBJC,") == 0) ||
505800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          (Section.find("__DATA, __objc_") == 0)) {
506800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
507800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
508800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
5098375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
5108375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Constant CFString instances are compiled in the following way:
5118375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the string buffer is emitted into
5128375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     __TEXT,__cstring,cstring_literals
5138375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the constant NSConstantString structure referencing that buffer
5148375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     is placed into __DATA,__cfstring
5158375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Therefore there's no point in placing redzones into __DATA,__cfstring.
5168375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Moreover, it causes the linker to crash on OS X 10.7
5178375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      if (Section.find("__DATA,__cfstring") == 0) {
5188375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        DEBUG(dbgs() << "Ignoring CFString: " << *G);
5198375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        continue;
5208375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      }
521800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
522800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
523800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalsToChange.push_back(G);
524800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
525800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
526800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
527800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
528800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
529800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
530800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
531800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
532800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
533800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
534800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
535800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
536800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               IntptrTy, IntptrTy, NULL);
537800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Constant *, 16> Initializers(n);
538800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
539800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
540800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
541800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
542800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
543800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
544800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
545208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
546800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t RightRedzoneSize = RedzoneSize +
547800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (RedzoneSize - (SizeInBytes % RedzoneSize));
548800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
549800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
550800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
551800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
552800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
553800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
554800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
555a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
556a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
557a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
558a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
559a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
560800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
561800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
562800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
563800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
564ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
565800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
566800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->setAlignment(RedzoneSize);
567800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
568800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
569800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
570800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
571800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
572800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
573f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
574800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
575800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
576800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
577800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
578800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
580800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
581800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
582800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
583800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
584800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
585800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
586800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
587800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
588800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
590800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
591800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
59255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
593800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
594800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
595800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
599800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6007bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
6017bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
6027bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
6037bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
6047bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
6057bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
6067bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
60755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanUnregisterGlobals =
60855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko      checkInterfaceFunction(M.getOrInsertFunction(
60955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          kAsanUnregisterGlobalsName,
61055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
6117bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
6127bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
6137bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
6147bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
6157bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
6167bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
6177bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
618800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
619800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
620800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
621800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
622800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// virtual
623800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::runOnModule(Module &M) {
624800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Initialize the private fields. No one has accessed them before.
625800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TD = getAnalysisIfAvailable<TargetData>();
626800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!TD)
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
628a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  BL.reset(new FunctionBlackList(ClBlackListFile));
629800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
630800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  C = &(M.getContext());
631800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LongSize = TD->getPointerSizeInBits();
632800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
633800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrPtrTy = PointerType::get(IntptrTy, 0);
634800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
635800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanCtorFunction = Function::Create(
636800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
637800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
638800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
640800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
641800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // call __asan_init in the module ctor.
642800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
64355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  AsanInitFunction = checkInterfaceFunction(
644800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
645800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
646800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall(AsanInitFunction);
647800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6489db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
6499db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
6509db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
6519db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
6529db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
6539db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
6549db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
6554f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
65611c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
6574f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany          M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
6589db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
6599db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
660f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
661f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
662f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
663f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
6649db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
66506fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  llvm::Triple targetTriple(M.getTargetTriple());
66606fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
66706fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov
66806fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
66906fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov    (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
670800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingOffsetLog >= 0) {
671800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClMappingOffsetLog == 0) {
672800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // special case
673800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 0;
674800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
675800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 1ULL << ClMappingOffsetLog;
676800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
677800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
678800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MappingScale = kDefaultShadowScale;
679800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingScale) {
680800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    MappingScale = ClMappingScale;
681800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
682800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
683800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
684800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  RedzoneSize = std::max(32, (int)(1 << MappingScale));
685800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
686800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool Res = false;
687800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
688800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClGlobals)
689800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= insertGlobalRedzones(M);
690800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6918c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingOffsetLog >= 0) {
6928c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Tell the run-time the current values of mapping offset and scale.
6938c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_offset =
6948c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
6958c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       ConstantInt::get(IntptrTy, MappingOffset),
6968c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       kAsanMappingOffsetName);
6978c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
6988c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_offset, true);
6998c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
7008c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingScale) {
7018c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_scale =
7028c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
7038c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           ConstantInt::get(IntptrTy, MappingScale),
7048c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           kAsanMappingScaleName);
7058c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
7068c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_scale, true);
7078c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
708800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
709800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
710800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
711800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (F->isDeclaration()) continue;
712800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= handleFunction(M, *F);
713800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
714800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7157bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
7169b02741d2284d9516a59666c211fe1f57e8803adKostya Serebryany
717800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return Res;
718800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
719800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
720a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
721a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
722a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
723a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
724a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
725a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
726a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
727a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
728a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
729a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
730a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
731a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
732a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
733a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
734a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
735a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
736800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::handleFunction(Module &M, Function &F) {
737800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
738800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
739a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
740a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // If needed, insert __asan_init before checking for AddressSafety attr.
741a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
742a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
7430307b9a88574d7e54459181afaa656ac92971847Kostya Serebryany  if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
744800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
745800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
746800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
747800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We want to instrument every address only once per basic block
748800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (unless there are calls between uses).
749800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
750800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
75195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
752e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
753800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
754800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
755800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
757800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
758324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
760800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
761bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
762e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
763800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
764800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
765800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
766800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
767800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
768800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
769800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
77095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany        if (CallInst *CI = dyn_cast<CallInst>(BI)) {
771800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
772800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
77395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          if (CI->doesNotReturn()) {
77495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany            NoReturnCalls.push_back(CI);
77595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          }
776800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
777800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
778800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
779800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
780324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
781324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
782324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
783800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
784800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
785800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7862735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  AsanFunctionContext AFC(F);
787c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
788800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
789800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
790800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
791800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
792800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
793800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
794e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
795c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        instrumentMop(AFC, Inst);
796800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
797c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
798800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
799800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
800800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
801800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
802800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << F);
803800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
804800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool ChangedStack = poisonStackInFunction(M, F);
80595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
80695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
80795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
80895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
80995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
81095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
81195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
81295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany                                         IRB.getVoidTy(), NULL));
81395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
81495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
81595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
816800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
817800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
818800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
819800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
820800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
821800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
822800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
823800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
824858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
825800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
826800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
827800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
828800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
829800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t RedzoneSize,
830800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
831800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
832800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < RedzoneSize;
833800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
834800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
835800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
836800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
837800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
838800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
839800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
840800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
841800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
842800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
843800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
844800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
845800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   IRBuilder<> IRB,
846800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Value *ShadowBase, bool DoPoison) {
847800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t ShadowRZSize = RedzoneSize >> MappingScale;
848800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
849800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
850800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
853800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
854800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
855800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
856800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
857800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
858800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
859800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
860800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
861800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
862800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
863800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
864800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
865800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
866800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
868800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize);
869800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
870800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
871800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
872800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
873800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
875800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
876800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
877800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
878800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                       (Pos >> MappingScale) - ShadowRZSize));
879800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
880800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
881800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
882800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
883800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        RedzoneSize,
884800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        1ULL << MappingScale,
885800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
886800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
887800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
888800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
889800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
890800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
893800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale));
894800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
895800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
896800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
897800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += RedzoneSize;
898800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
899800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
900800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9015a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// Workaround for bug 11395: we don't want to instrument stack in functions
9025a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
903d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany// FIXME: remove once the bug 11395 is fixed.
9045a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryanybool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
9055a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (LongSize != 32) return false;
9065a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  CallInst *CI = dyn_cast<CallInst>(I);
9075a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (!CI || !CI->isInlineAsm()) return false;
9085a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (CI->getNumArgOperands() <= 5) return false;
9095a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  // We have inline assembly with quite a few arguments.
9105a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  return true;
9115a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany}
9125a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany
913800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Find all static Alloca instructions and put
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// poisoned red zones around all of them.
915800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Then unpoison everything back before the function returns.
916800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
917800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Stack poisoning does not play well with exception handling.
918800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// When an exception is thrown, we essentially bypass the code
919800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// that unpoisones the stack. This is why the run-time library has
920800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
921800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// stack in the interceptor. This however does not work inside the
922800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// actual function which catches the exception. Most likely because the
923800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// compiler hoists the load of the shadow value somewhere too high.
924800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This causes asan to report a non-existing bug on 453.povray.
925800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// It sounds like an LLVM bug.
926800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
927800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClStack) return false;
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<AllocaInst*, 16> AllocaVec;
929800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 8> RetVec;
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t TotalSize = 0;
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Filter out Alloca instructions we want (and can) handle.
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Collect Ret instructions.
934800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
936800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    BasicBlock &BB = *FI;
937800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
938800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
939800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (isa<ReturnInst>(BI)) {
940800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          RetVec.push_back(BI);
941800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          continue;
942800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
943800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaInst *AI = dyn_cast<AllocaInst>(BI);
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI) continue;
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->isArrayAllocation()) continue;
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->isStaticAlloca()) continue;
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->getAllocatedType()->isSized()) continue;
949800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->getAlignment() > RedzoneSize) continue;
950800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaVec.push_back(AI);
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint64_t AlignedSize =  getAlignedAllocaSize(AI);
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TotalSize += AlignedSize;
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (AllocaVec.empty()) return false;
957800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool DoStackMalloc = ClUseAfterReturn
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
962800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
964800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MyAlloca->setAlignment(RedzoneSize);
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AsanStackMallocFunc = M.getOrInsertFunction(
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
981800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
987800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
988800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
989800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
990800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
992800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
993800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert((AlignedSize % RedzoneSize) == 0);
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AI->replaceAllUsesWith(
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IRB.CreateIntToPtr(
999800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            AI->getType()));
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize + RedzoneSize;
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1003800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1004800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1005800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
1006800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1007800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1008800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1010800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   ConstantInt::get(IntptrTy, LongSize/8));
1011800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Description = IRB.CreatePointerCast(
1013800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      createPrivateGlobalForString(M, StackDescription.str()),
1014800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IntptrTy);
1015800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
1016800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1017800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
1018800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1020800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1021800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AsanStackFreeFunc = NULL;
1022800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1023800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AsanStackFreeFunc = M.getOrInsertFunction(
1024800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackFreeName, IRB.getVoidTy(),
1025800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IntptrTy, IntptrTy, IntptrTy, NULL);
1026800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1027800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1028800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1029800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1030800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1031800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1032800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1033800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1034800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1036800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1039800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1040800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1041800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1042800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1043800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1044800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1045800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1046800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClDebugStack) {
1047800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << F);
1048800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1049800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1050800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1051800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1052