AddressSanitizer.cpp revision 11c2a47af825a0f89d75aaa97ad873ed2acef266
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);
1624f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany  Instruction *generateCrashCode(BasicBlock *BB, Value *Addr, Value *PC,
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//
254c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// If ThenBlock is zero, a new block is created and its terminator is returned.
2552735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany// Otherwize 0 is returned.
256c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
257c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                             BasicBlock *ThenBlock = 0) {
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();
2622735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  BranchInst *CheckTerm = 0;
263c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (!ThenBlock) {
264c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LLVMContext &C = Head->getParent()->getParent()->getContext();
265f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
266c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    CheckTerm = BranchInst::Create(Tail, ThenBlock);
267c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  }
268349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BranchInst *HeadNewTerm =
269349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
270349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
271349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth
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()));
32356139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany    InsertBefore = splitBlockAndInsertIfThen(Cmp);
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(
3944f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    BasicBlock *BB, Value *Addr, Value *PC,
3954f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex) {
396c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  IRBuilder<> IRB(BB->getFirstNonPHI());
3974f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany  CallInst *Call;
3984f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany  if (PC)
3994f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][AccessSizeIndex],
4004f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany                           Addr, PC);
4014f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany  else
4024f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
403f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
404f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
405f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
406f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
4073c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
408800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
409800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4102735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
411c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
412c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
413c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  size_t Granularity = 1 << MappingScale;
414c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
415c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
416c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
417c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
418c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
419c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
420c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
421c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
422c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
423c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      LastAccessedByte, IRB.getInt8Ty(), false);
424c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
425c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
426c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
427c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
428c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
429c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                         Instruction *OrigIns,
430800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
431800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
432800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
433800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
435800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale));
436800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
437800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
438800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
439800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
441800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
442800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
443800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
44411c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  BasicBlock *CrashBlock = BasicBlock::Create(*C, "crash_bb", &AFC.F);
44511c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  new UnreachableInst(*C, CrashBlock);
44611c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
44711c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  Instruction *Crash =
44811c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany      generateCrashCode(CrashBlock, AddrLong, 0, IsWrite, AccessSizeIndex);
44911c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
450800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
451800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t Granularity = 1 << MappingScale;
452800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize < 8 * Granularity) {
453f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *CheckTerm = splitBlockAndInsertIfThen(Cmp);
454f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    assert(CheckTerm->isUnconditional());
455f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
456c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
457c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
458f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
459f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
460c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
461c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    splitBlockAndInsertIfThen(Cmp, CrashBlock);
462800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
463800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
464800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
465800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
466800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
467800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
468800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::insertGlobalRedzones(Module &M) {
469800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
470800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
471800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
472800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       E = M.getGlobalList().end(); G != E; ++G) {
473800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = cast<PointerType>(G->getType())->getElementType();
474800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "GLOBAL: " << *G);
475800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
476800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!Ty->isSized()) continue;
477800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!G->hasInitializer()) continue;
4787cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Touch only those globals that will not be defined in other modules.
4797cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Don't handle ODR type linkages since other modules may be built w/o asan.
4802e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany    if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
4812e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::PrivateLinkage &&
4822e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::InternalLinkage)
483800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
484d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    // Two problems with thread-locals:
485d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - The address of the main thread's copy can't be computed at link-time.
486d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - Need to poison all copies, not just the main thread's one.
487d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    if (G->isThreadLocal())
488d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany      continue;
489800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // For now, just ignore this Alloca if the alignment is large.
490800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->getAlignment() > RedzoneSize) continue;
491800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
492800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all the globals with the names starting with "\01L_OBJC_".
493800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Many of those are put into the .cstring section. The linker compresses
494800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // that section by removing the spare \0s after the string terminator, so
495800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // our redzones get broken.
496800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if ((G->getName().find("\01L_OBJC_") == 0) ||
497800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (G->getName().find("\01l_OBJC_") == 0)) {
498800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
499800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
500800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
501800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
502800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->hasSection()) {
503800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      StringRef Section(G->getSection());
5048375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Ignore the globals from the __OBJC section. The ObjC runtime assumes
5058375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
5068375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // them.
507800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if ((Section.find("__OBJC,") == 0) ||
508800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          (Section.find("__DATA, __objc_") == 0)) {
509800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
510800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
511800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
5128375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
5138375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Constant CFString instances are compiled in the following way:
5148375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the string buffer is emitted into
5158375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     __TEXT,__cstring,cstring_literals
5168375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the constant NSConstantString structure referencing that buffer
5178375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     is placed into __DATA,__cfstring
5188375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Therefore there's no point in placing redzones into __DATA,__cfstring.
5198375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Moreover, it causes the linker to crash on OS X 10.7
5208375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      if (Section.find("__DATA,__cfstring") == 0) {
5218375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        DEBUG(dbgs() << "Ignoring CFString: " << *G);
5228375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        continue;
5238375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      }
524800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
525800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
526800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalsToChange.push_back(G);
527800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
528800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
529800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
530800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
531800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
532800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
533800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
534800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
535800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
536800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
537800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
538800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
539800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               IntptrTy, IntptrTy, NULL);
540800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Constant *, 16> Initializers(n);
541800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
542800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
543800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
544800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
545800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
546800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
547800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
548208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
549800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t RightRedzoneSize = RedzoneSize +
550800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (RedzoneSize - (SizeInBytes % RedzoneSize));
551800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
552800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
553800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
554800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
555800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
556800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
557800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
558a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
559a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
560a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
561a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
562a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
563800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
564800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
565800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
566800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
567ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
568800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
569800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->setAlignment(RedzoneSize);
570800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
571800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
572800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
573800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
574800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
575800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
576f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
577800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
578800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
580800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
581800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
582800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
583800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
584800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
585800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
586800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
587800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
588800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
590800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
591800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
592800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
593800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
594800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
59555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
599800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
600800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6037bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
6047bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
6057bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
6067bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
6077bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
6087bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
6097bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
61055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanUnregisterGlobals =
61155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko      checkInterfaceFunction(M.getOrInsertFunction(
61255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          kAsanUnregisterGlobalsName,
61355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
6147bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
6157bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
6167bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
6177bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
6187bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
6197bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
6207bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
621800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
622800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
623800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
624800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
625800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// virtual
626800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::runOnModule(Module &M) {
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Initialize the private fields. No one has accessed them before.
628800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TD = getAnalysisIfAvailable<TargetData>();
629800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!TD)
630800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
631a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  BL.reset(new FunctionBlackList(ClBlackListFile));
632800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
633800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  C = &(M.getContext());
634800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LongSize = TD->getPointerSizeInBits();
635800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
636800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrPtrTy = PointerType::get(IntptrTy, 0);
637800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
638800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanCtorFunction = Function::Create(
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
640800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
641800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
642800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
643800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
644800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // call __asan_init in the module ctor.
645800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
64655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  AsanInitFunction = checkInterfaceFunction(
647800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
648800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
649800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall(AsanInitFunction);
650800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6519db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
6529db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
6539db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
6549db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
6559db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
6569db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
6579db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
6584f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
65911c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
6604f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany          M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
6619db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
6629db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
663f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
664f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
665f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
666f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
6679db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
66806fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  llvm::Triple targetTriple(M.getTargetTriple());
66906fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
67006fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov
67106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
67206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov    (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
673800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingOffsetLog >= 0) {
674800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClMappingOffsetLog == 0) {
675800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // special case
676800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 0;
677800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
678800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 1ULL << ClMappingOffsetLog;
679800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
680800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
681800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MappingScale = kDefaultShadowScale;
682800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingScale) {
683800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    MappingScale = ClMappingScale;
684800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
685800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
686800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
687800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  RedzoneSize = std::max(32, (int)(1 << MappingScale));
688800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
689800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool Res = false;
690800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
691800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClGlobals)
692800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= insertGlobalRedzones(M);
693800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6948c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingOffsetLog >= 0) {
6958c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Tell the run-time the current values of mapping offset and scale.
6968c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_offset =
6978c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
6988c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       ConstantInt::get(IntptrTy, MappingOffset),
6998c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       kAsanMappingOffsetName);
7008c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
7018c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_offset, true);
7028c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
7038c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingScale) {
7048c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_scale =
7058c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
7068c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           ConstantInt::get(IntptrTy, MappingScale),
7078c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           kAsanMappingScaleName);
7088c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
7098c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_scale, true);
7108c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
711800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
712800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
713800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
714800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (F->isDeclaration()) continue;
715800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Res |= handleFunction(M, *F);
716800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
717800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7187bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
7199b02741d2284d9516a59666c211fe1f57e8803adKostya Serebryany
720800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return Res;
721800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
722800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
723a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
724a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
725a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
726a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
727a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
728a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
729a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
730a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
731a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
732a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
733a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
734a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
735a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
736a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
737a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
738a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
739800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::handleFunction(Module &M, Function &F) {
740800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
741800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
742a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
743a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // If needed, insert __asan_init before checking for AddressSafety attr.
744a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
745a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
7460307b9a88574d7e54459181afaa656ac92971847Kostya Serebryany  if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
747800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
748800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
749800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
750800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We want to instrument every address only once per basic block
751800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (unless there are calls between uses).
752800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
753800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
75495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
755e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
757800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
758800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
760800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
761324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
762800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
763800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
764bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
765e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
766800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
767800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
768800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
769800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
770800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
771800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
772800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
77395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany        if (CallInst *CI = dyn_cast<CallInst>(BI)) {
774800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
775800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
77695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          if (CI->doesNotReturn()) {
77795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany            NoReturnCalls.push_back(CI);
77895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          }
779800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
780800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
781800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
782800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
783324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
784324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
785324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
786800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
787800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
788800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7892735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  AsanFunctionContext AFC(F);
790c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
791800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
792800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
793800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
794800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
795800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
796800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
797e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
798c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        instrumentMop(AFC, Inst);
799800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
800c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
801800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
802800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
803800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
804800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
805800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << F);
806800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
807800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool ChangedStack = poisonStackInFunction(M, F);
80895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
80995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
81095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
81195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
81295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
81395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
81495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
81595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany                                         IRB.getVoidTy(), NULL));
81695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
81795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
81895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
819800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
820800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
821800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
822800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
823800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
824800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
825800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
826800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
827858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
828800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
829800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
830800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
831800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
832800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t RedzoneSize,
833800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
834800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
835800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < RedzoneSize;
836800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
837800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
838800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
839800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
840800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
841800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
842800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
843800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
844800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
845800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
846800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
847800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
848800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   IRBuilder<> IRB,
849800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Value *ShadowBase, bool DoPoison) {
850800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t ShadowRZSize = RedzoneSize >> MappingScale;
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
853800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
854800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
855800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
856800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
857800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
858800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
859800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
860800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
861800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
862800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
863800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
864800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
865800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
866800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
868800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
869800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
870800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
871800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize);
872800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
873800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
875800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
876800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
877800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
878800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
879800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
880800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
881800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                       (Pos >> MappingScale) - ShadowRZSize));
882800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
883800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
884800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
885800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
886800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        RedzoneSize,
887800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        1ULL << MappingScale,
888800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
889800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
890800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
893800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
894800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
895800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
896800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale));
897800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
898800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
899800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
900800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += RedzoneSize;
901800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
902800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
903800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9045a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// Workaround for bug 11395: we don't want to instrument stack in functions
9055a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
906d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany// FIXME: remove once the bug 11395 is fixed.
9075a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryanybool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
9085a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (LongSize != 32) return false;
9095a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  CallInst *CI = dyn_cast<CallInst>(I);
9105a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (!CI || !CI->isInlineAsm()) return false;
9115a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (CI->getNumArgOperands() <= 5) return false;
9125a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  // We have inline assembly with quite a few arguments.
9135a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  return true;
9145a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany}
9155a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany
916800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Find all static Alloca instructions and put
917800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// poisoned red zones around all of them.
918800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Then unpoison everything back before the function returns.
919800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
920800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Stack poisoning does not play well with exception handling.
921800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// When an exception is thrown, we essentially bypass the code
922800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// that unpoisones the stack. This is why the run-time library has
923800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
924800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// stack in the interceptor. This however does not work inside the
925800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// actual function which catches the exception. Most likely because the
926800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// compiler hoists the load of the shadow value somewhere too high.
927800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This causes asan to report a non-existing bug on 453.povray.
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// It sounds like an LLVM bug.
929800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClStack) return false;
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<AllocaInst*, 16> AllocaVec;
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 8> RetVec;
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t TotalSize = 0;
934800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Filter out Alloca instructions we want (and can) handle.
936800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Collect Ret instructions.
937800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
938800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
939800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    BasicBlock &BB = *FI;
940800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
941800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
942800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (isa<ReturnInst>(BI)) {
943800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          RetVec.push_back(BI);
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          continue;
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaInst *AI = dyn_cast<AllocaInst>(BI);
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI) continue;
949800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->isArrayAllocation()) continue;
950800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->isStaticAlloca()) continue;
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->getAllocatedType()->isSized()) continue;
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->getAlignment() > RedzoneSize) continue;
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaVec.push_back(AI);
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint64_t AlignedSize =  getAlignedAllocaSize(AI);
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TotalSize += AlignedSize;
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
957800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (AllocaVec.empty()) return false;
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
962800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool DoStackMalloc = ClUseAfterReturn
964800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MyAlloca->setAlignment(RedzoneSize);
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AsanStackMallocFunc = M.getOrInsertFunction(
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
981800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
987800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
988800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
989800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
990800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
992800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
993800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
999800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert((AlignedSize % RedzoneSize) == 0);
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AI->replaceAllUsesWith(
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IRB.CreateIntToPtr(
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1003800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            AI->getType()));
1004800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize + RedzoneSize;
1005800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1006800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1007800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1008800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1010800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1011800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1013800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   ConstantInt::get(IntptrTy, LongSize/8));
1014800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1015800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Description = IRB.CreatePointerCast(
1016800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      createPrivateGlobalForString(M, StackDescription.str()),
1017800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IntptrTy);
1018800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1020800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
1021800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1022800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1023800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1024800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AsanStackFreeFunc = NULL;
1025800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1026800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AsanStackFreeFunc = M.getOrInsertFunction(
1027800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackFreeName, IRB.getVoidTy(),
1028800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IntptrTy, IntptrTy, IntptrTy, NULL);
1029800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1030800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1031800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1032800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1033800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1034800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1036800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1039800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
1040800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1041800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1042800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1043800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1044800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1045800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1046800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1047800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1048800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1049800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClDebugStack) {
1050800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << F);
1051800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1052800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1053800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1054800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1055