AddressSanitizer.cpp revision 2735cf4aa52e31b8d2de90f836c3ad991215e04e
1800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
3800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//                     The LLVM Compiler Infrastructure
4800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
5800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is distributed under the University of Illinois Open Source
6800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// License. See LICENSE.TXT for details.
7800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
8800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
9800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
10800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is a part of AddressSanitizer, an address sanity checker.
11800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Details of the algorithm:
12800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
14800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
15800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
16800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#define DEBUG_TYPE "asan"
17800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
18a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany#include "FunctionBlackList.h"
1906cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Function.h"
2006cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IRBuilder.h"
2106cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/IntrinsicInst.h"
2206cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/LLVMContext.h"
2306cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Module.h"
2406cb8ed00696eb14d1b831921452e50ec0568ea2Chandler Carruth#include "llvm/Type.h"
25800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.h"
26800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/OwningPtr.h"
27800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallSet.h"
28800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallString.h"
29800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallVector.h"
30800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/StringExtras.h"
3106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov#include "llvm/ADT/Triple.h"
32800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
33800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
34800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
35800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
36800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
37800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetData.h"
38800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetMachine.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Instrumentation.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
42800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <string>
44800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
46800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
47800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
48800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
49800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
5106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanovstatic const uint64_t kDefaultShadowOffsetAndroid = 0;
52800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanModuleCtorName = "asan.module_ctor";
587bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanModuleDtorName = "asan.module_dtor";
597bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const int   kAsanCtorAndCtorPriority = 1;
60800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanReportErrorTemplate = "__asan_report_";
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanRegisterGlobalsName = "__asan_register_globals";
627bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
63800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanInitName = "__asan_init";
6495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryanystatic const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
65800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingOffsetName = "__asan_mapping_offset";
66800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingScaleName = "__asan_mapping_scale";
67800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackMallocName = "__asan_stack_malloc";
68800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackFreeName = "__asan_stack_free";
69800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
70800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
71800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
72800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
73800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
74800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
75c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
76c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic const size_t kNumberOfAccessSizes = 5;
77c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
78800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
79800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
80800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
81800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
82800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
83800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
84800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
85e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
86e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
87e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
88c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic cl::opt<bool> ClMergeCallbacks("asan-merge-callbacks",
89c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany       cl::desc("merge __asan_report_ callbacks to create fewer BBs"),
90c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany       cl::Hidden, cl::init(false));
91c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// This flag limits the number of instructions to be instrumented
92324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
93324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
94324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
95324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
96324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
97324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
98324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
99800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
100800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
101800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
103800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
104800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
105800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -fasan-blacklist.
111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string>  ClBlackListFile("asan-blacklist",
112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("File containing the list of functions to ignore "
113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
141800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
146800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
147c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany/// An object of this type is created while instrumenting every function.
148c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystruct AsanFunctionContext {
1492735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  AsanFunctionContext(Function &Function) : F(Function), CrashBlock() { }
150c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
1512735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Function &F;
152c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // These are initially zero. If we require at least one call to
153c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // __asan_report_{read,write}{1,2,4,8,16}, an appropriate BB is created.
154c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  BasicBlock *CrashBlock[2][kNumberOfAccessSizes];
155c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany};
156c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystruct AddressSanitizer : public ModulePass {
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AddressSanitizer();
16025878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  virtual const char *getPassName() const;
161c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
162c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentAddress(AsanFunctionContext &AFC,
163c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                         Instruction *OrigIns, IRBuilder<> &IRB,
164800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite);
165c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
166c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
167c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Instruction *generateCrashCode(BasicBlock *BB, Value *Addr,
1682735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex);
169c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
170c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
171c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Instruction *OrigIns, Value *Addr,
172c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
173800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
174800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool handleFunction(Module &M, Function &F);
176a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool poisonStackInFunction(Module &M, Function &F);
178800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  virtual bool runOnModule(Module &M);
179800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool insertGlobalRedzones(Module &M);
180800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
181800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = AI->getAllocatedType();
186d8313be41031e4d768f5b38199904d4debff88cdEvgeniy Stepanov    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return SizeInBytes;
188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
189800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedSize(uint64_t SizeInBytes) {
190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return ((SizeInBytes + RedzoneSize - 1)
191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            / RedzoneSize) * RedzoneSize;
192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
193800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
195800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return getAlignedSize(SizeInBytes);
196800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
197800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
19855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *checkInterfaceFunction(Constant *FuncOrBitcast);
199800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
200800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                   Value *ShadowBase, bool DoPoison);
2015a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
202800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TargetData *TD;
205800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t MappingOffset;
206800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int MappingScale;
207800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t RedzoneSize;
208800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
209800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
210800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrPtrTy;
211800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
212800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
213800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *CtorInsertBefore;
214a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  OwningPtr<FunctionBlackList> BL;
2159db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
2169db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
217800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
218c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
219800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
220800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
221800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
222800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
223800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
224800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyAddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
226800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyModulePass *llvm::createAddressSanitizerPass() {
227800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new AddressSanitizer();
228800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
229800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
23025878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenkoconst char *AddressSanitizer::getPassName() const {
23125878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko  return "AddressSanitizer";
23225878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
23325878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
2342735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
2352735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  size_t Res = CountTrailingZeros_32(TypeSize / 8);
2362735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
2372735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
2382735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
2392735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
240800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
241800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
24218c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
243800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new GlobalVariable(M, StrConst->getType(), true,
244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst, "");
245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
246800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Split the basic block and insert an if-then code.
248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Before:
249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
25056139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//   Cmp
251800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
252800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// After:
253800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Head
254800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   if (Cmp)
25556139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany//     ThenBlock
256800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//   Tail
257800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
258c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// If ThenBlock is zero, a new block is created and its terminator is returned.
2592735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany// Otherwize 0 is returned.
260c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
261c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                             BasicBlock *ThenBlock = 0) {
26256139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany  Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
263800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *Head = SplitBefore->getParent();
264349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
265800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TerminatorInst *HeadOldTerm = Head->getTerminator();
2662735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  BranchInst *CheckTerm = 0;
267c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (!ThenBlock) {
268c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LLVMContext &C = Head->getParent()->getParent()->getContext();
269c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    ThenBlock = BasicBlock::Create(C, "", Head->getParent());
270c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    CheckTerm = BranchInst::Create(Tail, ThenBlock);
271c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  }
272349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  BranchInst *HeadNewTerm =
273349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
274349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
275349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth
276349f14c72cbcd3c50091d20a874967aca5f2f746Chandler Carruth  return CheckTerm;
277800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
278800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
279800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
280800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
281800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Shadow = IRB.CreateLShr(Shadow, MappingScale);
282800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (MappingOffset == 0)
283800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
284800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
285800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
286800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               MappingOffset));
287800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
288800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
289c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
290c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    AsanFunctionContext &AFC, Instruction *OrigIns,
291800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
292800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
294800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
295c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
296800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
297800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
298800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
300800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *SizeMinusOne = IRB.CreateSub(
301800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Size, ConstantInt::get(Size->getType(), 1));
302800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
303800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
305c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
306800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
307800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
308800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
309800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
310c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
311c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                              MemIntrinsic *MI) {
312800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
313800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
3142735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
317800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
318800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
319800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
320800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
321800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
322800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
323800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
324800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
32656139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
32756139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany    InsertBefore = splitBlockAndInsertIfThen(Cmp);
328800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
329800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
330c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
331800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
332c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
333800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
334800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
335800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
336e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
337e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
338e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
339800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
340e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
341e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
342800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
343800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
344e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
345e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
346e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
347e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
348e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
349e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
350e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
351e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
352e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
353e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
354e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
355e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
356e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
357e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
358e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
359e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
360800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
361800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
362c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
363e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
364e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
365e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
366800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
367800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // We are accessing a global scalar variable. Nothing to catch here.
368800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
369800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
370800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
371800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
372800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
373800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
374800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
375800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
376800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize != 8  && TypeSize != 16 &&
377800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
378800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all unusual sizes.
379800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
380800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
381800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
382800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
383c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
384800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
385800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
38655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
38755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
38855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
38955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
39055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander PotapenkoFunction *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
39155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
39255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
39355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
39455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
39555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
39655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
397800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
3982735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    BasicBlock *BB, Value *Addr, bool IsWrite, size_t AccessSizeIndex) {
399c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  IRBuilder<> IRB(BB->getFirstNonPHI());
4009db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
4019db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany                                  Addr);
4023c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  Call->setDoesNotReturn();
4033c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
404800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
405800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4062735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
407c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
408c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
409c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  size_t Granularity = 1 << MappingScale;
410c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
411c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
412c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
413c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
414c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
415c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
416c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
417c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
418c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
419c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      LastAccessedByte, IRB.getInt8Ty(), false);
420c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
421c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
422c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
423c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
424c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
425c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                         Instruction *OrigIns,
426800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
427800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
428800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
429800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
430800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
431800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale));
432800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
433800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
435800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
436800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
437800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
438800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
439800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4402735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  BasicBlock *CrashBlock = 0;
441c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (ClMergeCallbacks) {
4422735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    BasicBlock **Cached =
4432735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany        &AFC.CrashBlock[IsWrite][TypeSizeToSizeIndex(TypeSize)];
4442735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    if (!*Cached) {
4452735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany      BasicBlock *BB = BasicBlock::Create(*C, "crash_bb", &AFC.F);
4462735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany      new UnreachableInst(*C, BB);
4472735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany      *Cached = BB;
4482735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    }
4492735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    CrashBlock = *Cached;
450c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
4512735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    CrashBlock = BasicBlock::Create(*C, "crash_bb", &AFC.F);
452c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    new UnreachableInst(*C, CrashBlock);
4532735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
454c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Instruction *Crash =
4552735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany        generateCrashCode(CrashBlock, AddrLong, IsWrite, AccessSizeIndex);
456c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Crash->setDebugLoc(OrigIns->getDebugLoc());
457c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  }
458800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
459800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t Granularity = 1 << MappingScale;
460800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize < 8 * Granularity) {
461c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
462c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
463c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
464c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    splitBlockAndInsertIfThen(Cmp2, CrashBlock);
465c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
466c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    splitBlockAndInsertIfThen(Cmp, CrashBlock);
467800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
468800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
469800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
470800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
471800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
472800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
473800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::insertGlobalRedzones(Module &M) {
474800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
475800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
476800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
477800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       E = M.getGlobalList().end(); G != E; ++G) {
478800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = cast<PointerType>(G->getType())->getElementType();
479800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "GLOBAL: " << *G);
480800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
481800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!Ty->isSized()) continue;
482800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (!G->hasInitializer()) continue;
4837cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Touch only those globals that will not be defined in other modules.
4847cf2a04361e8613264498e50babe52d65c070473Kostya Serebryany    // Don't handle ODR type linkages since other modules may be built w/o asan.
4852e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany    if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
4862e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::PrivateLinkage &&
4872e7fb2f73641f1f1ca385fe7777075945bf4ca24Kostya Serebryany        G->getLinkage() != GlobalVariable::InternalLinkage)
488800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
489d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    // Two problems with thread-locals:
490d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - The address of the main thread's copy can't be computed at link-time.
491d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    //   - Need to poison all copies, not just the main thread's one.
492d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany    if (G->isThreadLocal())
493d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany      continue;
494800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // For now, just ignore this Alloca if the alignment is large.
495800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->getAlignment() > RedzoneSize) continue;
496800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
497800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all the globals with the names starting with "\01L_OBJC_".
498800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Many of those are put into the .cstring section. The linker compresses
499800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // that section by removing the spare \0s after the string terminator, so
500800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // our redzones get broken.
501800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if ((G->getName().find("\01L_OBJC_") == 0) ||
502800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (G->getName().find("\01l_OBJC_") == 0)) {
503800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
504800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      continue;
505800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
506800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
507800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (G->hasSection()) {
508800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      StringRef Section(G->getSection());
5098375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Ignore the globals from the __OBJC section. The ObjC runtime assumes
5108375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
5118375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // them.
512800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if ((Section.find("__OBJC,") == 0) ||
513800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          (Section.find("__DATA, __objc_") == 0)) {
514800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
515800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
516800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
5178375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
5188375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Constant CFString instances are compiled in the following way:
5198375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the string buffer is emitted into
5208375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     __TEXT,__cstring,cstring_literals
5218375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //  -- the constant NSConstantString structure referencing that buffer
5228375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      //     is placed into __DATA,__cfstring
5238375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Therefore there's no point in placing redzones into __DATA,__cfstring.
5248375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      // Moreover, it causes the linker to crash on OS X 10.7
5258375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      if (Section.find("__DATA,__cfstring") == 0) {
5268375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        DEBUG(dbgs() << "Ignoring CFString: " << *G);
5278375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko        continue;
5288375bc923638299410e75e8f668524fc1aa113bdAlexander Potapenko      }
529800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
530800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
531800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalsToChange.push_back(G);
532800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
533800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
534800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
535800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
536800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
537800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
538800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
539800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
540800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
541800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
542800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
543800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
544800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               IntptrTy, IntptrTy, NULL);
545800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Constant *, 16> Initializers(n);
546800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
547800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
548800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
549800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
550800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
551800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
552800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
553208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
554800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t RightRedzoneSize = RedzoneSize +
555800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (RedzoneSize - (SizeInBytes % RedzoneSize));
556800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
557800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
558800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
559800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
560800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
561800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
562800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
563a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
564a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
565a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
566a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
567a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
568800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
569800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
570800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
571800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
572ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
573800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
574800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->setAlignment(RedzoneSize);
575800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
576800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
577800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
578800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
580800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
581f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
582800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
583800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
584800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
585800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
586800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
587800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
588800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
590800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
591800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
592800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
593800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
594800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
595800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
599800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
60055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
603800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
604800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
605800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
606800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
607800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6087bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
6097bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
6107bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
6117bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
6127bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
6137bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
6147bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
61555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  Function *AsanUnregisterGlobals =
61655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko      checkInterfaceFunction(M.getOrInsertFunction(
61755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          kAsanUnregisterGlobalsName,
61855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko          IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
6197bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
6207bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
6217bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
6227bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
6237bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
6247bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
6257bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
626800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
628800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
629800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
630800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// virtual
631800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::runOnModule(Module &M) {
632800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Initialize the private fields. No one has accessed them before.
633800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  TD = getAnalysisIfAvailable<TargetData>();
634800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!TD)
635800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
636a1c45044099cf7fb4a072f1326f164706d5bb2e2Kostya Serebryany  BL.reset(new FunctionBlackList(ClBlackListFile));
637800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
638800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  C = &(M.getContext());
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LongSize = TD->getPointerSizeInBits();
640800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
641800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IntptrPtrTy = PointerType::get(IntptrTy, 0);
642800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
643800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanCtorFunction = Function::Create(
644800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
645800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
646800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
647800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
648800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
649800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // call __asan_init in the module ctor.
650800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(CtorInsertBefore);
65155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  AsanInitFunction = checkInterfaceFunction(
652800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
653800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
654800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall(AsanInitFunction);
655800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6569db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
6579db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
6589db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
6599db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
6609db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
6619db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
6629db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
6639db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
6649db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany        M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
6659db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
6669db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
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
8052735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  if (NumInstrumented) {
8062735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    for (size_t IsWrite = 0; IsWrite <= 1; IsWrite++) {
8072735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany      for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
8082735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany           AccessSizeIndex++) {
8092735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany        BasicBlock *BB = AFC.CrashBlock[IsWrite][AccessSizeIndex];
8102735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany        if (!BB) continue;
8112735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany        generateCrashCode(BB, ConstantInt::get(IntptrTy, 0),
8122735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany                          IsWrite, AccessSizeIndex);
8132735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany      }
8142735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany    }
8152735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  }
8162735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
817800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << F);
818800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
819800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool ChangedStack = poisonStackInFunction(M, F);
82095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
82195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
82295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
82395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
82495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
82595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
82695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
82795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany                                         IRB.getVoidTy(), NULL));
82895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
82995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
83095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
831800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
832800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
833800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
834800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
835800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
836800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
837800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
838800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
839858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
840800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
841800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
842800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
843800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
844800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t RedzoneSize,
845800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
846800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
847800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < RedzoneSize;
848800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
849800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
850800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
853800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
854800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
855800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
856800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
857800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
858800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
859800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyvoid AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
860800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   IRBuilder<> IRB,
861800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Value *ShadowBase, bool DoPoison) {
862800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t ShadowRZSize = RedzoneSize >> MappingScale;
863800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
864800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
865800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
866800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
868800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
869800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
870800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
871800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
872800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
873800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
875800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
876800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
877800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
878800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
879800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
880800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
881800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
882800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
883800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize);
884800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
885800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
886800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
887800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
888800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
889800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
890800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
893800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                       (Pos >> MappingScale) - ShadowRZSize));
894800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
895800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
896800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
897800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
898800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        RedzoneSize,
899800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        1ULL << MappingScale,
900800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
901800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
902800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
903800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
904800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
905800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
906800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
907800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
908800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale));
909800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
910800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
911800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
912800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += RedzoneSize;
913800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
915800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9165a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// Workaround for bug 11395: we don't want to instrument stack in functions
9175a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
918d2703dec271d82c8c9d22afb835c07730fd25d47Kostya Serebryany// FIXME: remove once the bug 11395 is fixed.
9195a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryanybool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
9205a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (LongSize != 32) return false;
9215a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  CallInst *CI = dyn_cast<CallInst>(I);
9225a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (!CI || !CI->isInlineAsm()) return false;
9235a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  if (CI->getNumArgOperands() <= 5) return false;
9245a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  // We have inline assembly with quite a few arguments.
9255a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  return true;
9265a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany}
9275a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Find all static Alloca instructions and put
929800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// poisoned red zones around all of them.
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Then unpoison everything back before the function returns.
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Stack poisoning does not play well with exception handling.
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// When an exception is thrown, we essentially bypass the code
934800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// that unpoisones the stack. This is why the run-time library has
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
936800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// stack in the interceptor. This however does not work inside the
937800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// actual function which catches the exception. Most likely because the
938800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// compiler hoists the load of the shadow value somewhere too high.
939800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This causes asan to report a non-existing bug on 453.povray.
940800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// It sounds like an LLVM bug.
941800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanybool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
942800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClStack) return false;
943800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<AllocaInst*, 16> AllocaVec;
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 8> RetVec;
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t TotalSize = 0;
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Filter out Alloca instructions we want (and can) handle.
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Collect Ret instructions.
949800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
950800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    BasicBlock &BB = *FI;
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (isa<ReturnInst>(BI)) {
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          RetVec.push_back(BI);
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          continue;
957800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaInst *AI = dyn_cast<AllocaInst>(BI);
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI) continue;
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->isArrayAllocation()) continue;
962800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->isStaticAlloca()) continue;
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (!AI->getAllocatedType()->isSized()) continue;
964800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (AI->getAlignment() > RedzoneSize) continue;
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      AllocaVec.push_back(AI);
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint64_t AlignedSize =  getAlignedAllocaSize(AI);
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TotalSize += AlignedSize;
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (AllocaVec.empty()) return false;
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  bool DoStackMalloc = ClUseAfterReturn
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
981800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MyAlloca->setAlignment(RedzoneSize);
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
987800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
988800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
989800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
990800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AsanStackMallocFunc = M.getOrInsertFunction(
992800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
993800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
999800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t Pos = RedzoneSize;
1003800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
1004800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1005800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1006800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1007800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
1008800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
1010800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1011800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert((AlignedSize % RedzoneSize) == 0);
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AI->replaceAllUsesWith(
1013800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IRB.CreateIntToPtr(
1014800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1015800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            AI->getType()));
1016800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize + RedzoneSize;
1017800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1018800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1020800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
1021800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1022800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1023800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
1024800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1025800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   ConstantInt::get(IntptrTy, LongSize/8));
1026800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1027800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Description = IRB.CreatePointerCast(
1028800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      createPrivateGlobalForString(M, StackDescription.str()),
1029800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IntptrTy);
1030800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
1031800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1032800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
1033800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1034800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1036800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AsanStackFreeFunc = NULL;
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AsanStackFreeFunc = M.getOrInsertFunction(
1039800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        kAsanStackFreeName, IRB.getVoidTy(),
1040800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        IntptrTy, IntptrTy, IntptrTy, NULL);
1041800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1042800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1043800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1044800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1045800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1046800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1047800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1048800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1049800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1050800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1051800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
1052800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1053800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1054800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1055800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1056800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1057800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1058800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1059800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1060800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1061800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClDebugStack) {
1062800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    DEBUG(dbgs() << F);
1063800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1064800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1065800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1066800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1067