blob: e095ed5f03398ee13a5282bcaae8c875d89d976b [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000019#include "llvm/ADT/DenseSet.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000020#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000024#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000025#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000028#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000033#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000036#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
38#include "llvm/IR/Type.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000042#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000043#include "llvm/Support/SwapByteOrder.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000044#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000045#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000047#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000048#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000049#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000050#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000052#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000053
54using namespace llvm;
55
Chandler Carruth964daaa2014-04-22 02:55:47 +000056#define DEBUG_TYPE "asan"
57
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000058static const uint64_t kDefaultShadowScale = 3;
59static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000060static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000061static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000062static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000063static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000064static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kostya Serebryany231bd082014-11-11 23:02:57 +000065static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000066static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
67static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000068
Kostya Serebryany6805de52013-09-10 13:16:56 +000069static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000070static const size_t kMaxStackMallocSize = 1 << 16; // 64K
71static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
72static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
73
Craig Topperd3a34f82013-07-16 01:17:10 +000074static const char *const kAsanModuleCtorName = "asan.module_ctor";
75static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000076static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000077static const char *const kAsanReportErrorTemplate = "__asan_report_";
78static const char *const kAsanReportLoadN = "__asan_report_load_n";
79static const char *const kAsanReportStoreN = "__asan_report_store_n";
80static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000081static const char *const kAsanUnregisterGlobalsName =
82 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000083static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
84static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000085static const char *const kAsanInitName = "__asan_init_v4";
Kostya Serebryany796f6552014-02-27 12:45:36 +000086static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
87static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000089static const int kMaxAsanStackMallocSizeClass = 10;
90static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
91static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000093static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +000094static const char *const kAsanPoisonStackMemoryName =
95 "__asan_poison_stack_memory";
96static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000097 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000098
Kostya Serebryanyf3223822013-09-18 14:07:14 +000099static const char *const kAsanOptionDetectUAR =
100 "__asan_option_detect_stack_use_after_return";
101
David Blaikieeacc2872013-09-18 00:11:27 +0000102#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000103static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000104#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000105
Kostya Serebryany874dae62012-07-16 16:15:40 +0000106// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
107static const size_t kNumberOfAccessSizes = 5;
108
Yury Gribov55441bb2014-11-21 10:29:50 +0000109static const unsigned kAllocaRzSize = 32;
110static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
111static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
112static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
113static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
114
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000115// Command-line flags.
116
117// This flag may need to be replaced with -f[no-]asan-reads.
118static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
119 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
120static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
121 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000122static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
123 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
124 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000125static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
126 cl::desc("use instrumentation with slow path for all accesses"),
127 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000128// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000129// in any given BB. Normally, this should be set to unlimited (INT_MAX),
130// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
131// set it to 10000.
132static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
133 cl::init(10000),
134 cl::desc("maximal number of instructions to instrument in any given BB"),
135 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000136// This flag may need to be replaced with -f[no]asan-stack.
137static cl::opt<bool> ClStack("asan-stack",
138 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000139static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000140 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000141// This flag may need to be replaced with -f[no]asan-globals.
142static cl::opt<bool> ClGlobals("asan-globals",
143 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000144static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000145 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000146static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
147 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000148 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000149static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
150 cl::desc("Realign stack to the value of this flag (power of two)"),
151 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000152static cl::opt<int> ClInstrumentationWithCallsThreshold(
153 "asan-instrumentation-with-call-threshold",
154 cl::desc("If the function being instrumented contains more than "
155 "this number of memory accesses, use callbacks instead of "
156 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000157 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000158static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
159 "asan-memory-access-callback-prefix",
160 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
161 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000162static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
163 cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000164
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000165// This is an experimental feature that will allow to choose between
166// instrumented and non-instrumented code at link-time.
167// If this option is on, just before instrumenting a function we create its
168// clone; if the function is not changed by asan the clone is deleted.
169// If we end up with a clone, we put the instrumented function into a section
170// called "ASAN" and the uninstrumented function into a section called "NOASAN".
171//
172// This is still a prototype, we need to figure out a way to keep two copies of
173// a function so that the linker can easily choose one of them.
174static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
175 cl::desc("Keep uninstrumented copies of functions"),
176 cl::Hidden, cl::init(false));
177
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000178// These flags allow to change the shadow mapping.
179// The shadow mapping looks like
180// Shadow = (Mem >> scale) + (1 << offset_log)
181static cl::opt<int> ClMappingScale("asan-mapping-scale",
182 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000183
184// Optimization flags. Not user visible, used mostly for testing
185// and benchmarking the tool.
186static cl::opt<bool> ClOpt("asan-opt",
187 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
188static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
189 cl::desc("Instrument the same temp just once"), cl::Hidden,
190 cl::init(true));
191static cl::opt<bool> ClOptGlobals("asan-opt-globals",
192 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
193
Alexey Samsonovdf624522012-11-29 18:14:24 +0000194static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
195 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
196 cl::Hidden, cl::init(false));
197
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000198// Debug flags.
199static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
200 cl::init(0));
201static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
202 cl::Hidden, cl::init(0));
203static cl::opt<std::string> ClDebugFunc("asan-debug-func",
204 cl::Hidden, cl::desc("Debug func"));
205static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
206 cl::Hidden, cl::init(-1));
207static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
208 cl::Hidden, cl::init(-1));
209
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000210STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
211STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
212STATISTIC(NumOptimizedAccessesToGlobalArray,
213 "Number of optimized accesses to global arrays");
214STATISTIC(NumOptimizedAccessesToGlobalVar,
215 "Number of optimized accesses to global vars");
216
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000217namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000218/// Frontend-provided metadata for source location.
219struct LocationMetadata {
220 StringRef Filename;
221 int LineNo;
222 int ColumnNo;
223
224 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
225
226 bool empty() const { return Filename.empty(); }
227
228 void parse(MDNode *MDN) {
229 assert(MDN->getNumOperands() == 3);
230 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
231 Filename = MDFilename->getString();
232 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
233 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
234 }
235};
236
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000237/// Frontend-provided metadata for global variables.
238class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000239 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000240 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000241 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000242 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000243 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000244 LocationMetadata SourceLoc;
245 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000246 bool IsDynInit;
247 bool IsBlacklisted;
248 };
249
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000250 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000251
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000252 void init(Module& M) {
253 assert(!inited_);
254 inited_ = true;
255 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
256 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000257 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000258 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000259 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000260 assert(MDN->getNumOperands() == 5);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000261 Value *V = MDN->getOperand(0);
262 // The optimizer may optimize away a global entirely.
263 if (!V)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000264 continue;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000265 GlobalVariable *GV = cast<GlobalVariable>(V);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000266 // We can already have an entry for GV if it was merged with another
267 // global.
268 Entry &E = Entries[GV];
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000269 if (Value *Loc = MDN->getOperand(1))
270 E.SourceLoc.parse(cast<MDNode>(Loc));
Alexey Samsonov15c96692014-07-12 00:42:52 +0000271 if (Value *Name = MDN->getOperand(2)) {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000272 MDString *MDName = cast<MDString>(Name);
273 E.Name = MDName->getString();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000274 }
275 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000276 E.IsDynInit |= IsDynInit->isOne();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000277 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000278 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000279 }
280 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000281
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000282 /// Returns metadata entry for a given global.
283 Entry get(GlobalVariable *G) const {
284 auto Pos = Entries.find(G);
285 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000286 }
287
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000288 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000289 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000290 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000291};
292
Alexey Samsonov1345d352013-01-16 13:23:28 +0000293/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000294/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000295struct ShadowMapping {
296 int Scale;
297 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000298 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000299};
300
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000301static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000302 llvm::Triple TargetTriple(M.getTargetTriple());
303 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000304 bool IsIOS = TargetTriple.isiOS();
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000305 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000306 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000307 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
308 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000309 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000310 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
311 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000312 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
313 TargetTriple.getArch() == llvm::Triple::mips64el;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000314
315 ShadowMapping Mapping;
316
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000317 if (LongSize == 32) {
318 if (IsAndroid)
319 Mapping.Offset = 0;
320 else if (IsMIPS32)
321 Mapping.Offset = kMIPS32_ShadowOffset32;
322 else if (IsFreeBSD)
323 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000324 else if (IsIOS)
325 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000326 else
327 Mapping.Offset = kDefaultShadowOffset32;
328 } else { // LongSize == 64
329 if (IsPPC64)
330 Mapping.Offset = kPPC64_ShadowOffset64;
331 else if (IsFreeBSD)
332 Mapping.Offset = kFreeBSD_ShadowOffset64;
333 else if (IsLinux && IsX86_64)
334 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000335 else if (IsMIPS64)
336 Mapping.Offset = kMIPS64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000337 else
338 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000339 }
340
341 Mapping.Scale = kDefaultShadowScale;
342 if (ClMappingScale) {
343 Mapping.Scale = ClMappingScale;
344 }
345
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000346 // OR-ing shadow offset if more efficient (at least on x86) if the offset
347 // is a power of two, but on ppc64 we have to use add since the shadow
348 // offset is not necessary 1/8-th of the address space.
349 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
350
Alexey Samsonov1345d352013-01-16 13:23:28 +0000351 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000352}
353
Alexey Samsonov1345d352013-01-16 13:23:28 +0000354static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000355 // Redzone used for stack and globals is at least 32 bytes.
356 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000357 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000358}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000359
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000360/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000361struct AddressSanitizer : public FunctionPass {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000362 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000363 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000364 return "AddressSanitizerFunctionPass";
365 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000366 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000367 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000368 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
369 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000370 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000371 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
372 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000373 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000374 bool IsWrite, size_t AccessSizeIndex,
375 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000376 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000377 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000378 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000379 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000380 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000381 static char ID; // Pass identification, replacement for typeid
382
383 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000384 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000385
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000386 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000387 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000388
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000389 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000390 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000391 int LongSize;
392 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000393 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000394 Function *AsanCtorFunction;
395 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000396 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000397 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000398 // This array is indexed by AccessIsWrite and log2(AccessSize).
399 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000400 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000401 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000402 Function *AsanErrorCallbackSized[2],
403 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000404 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000405 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000406 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000407
408 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000409};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000410
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000411class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000412 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000413 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000414 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000415 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000416 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000417 return "AddressSanitizerModule";
418 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000419
Kostya Serebryany20a79972012-11-22 03:18:50 +0000420 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000421 void initializeCallbacks(Module &M);
422
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000423 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000424 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000425 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000426 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000427 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000428 return RedzoneSizeForScale(Mapping.Scale);
429 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000430
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000431 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000432 Type *IntptrTy;
433 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000434 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000435 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000436 Function *AsanPoisonGlobals;
437 Function *AsanUnpoisonGlobals;
438 Function *AsanRegisterGlobals;
439 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000440};
441
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000442// Stack poisoning does not play well with exception handling.
443// When an exception is thrown, we essentially bypass the code
444// that unpoisones the stack. This is why the run-time library has
445// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
446// stack in the interceptor. This however does not work inside the
447// actual function which catches the exception. Most likely because the
448// compiler hoists the load of the shadow value somewhere too high.
449// This causes asan to report a non-existing bug on 453.povray.
450// It sounds like an LLVM bug.
451struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
452 Function &F;
453 AddressSanitizer &ASan;
454 DIBuilder DIB;
455 LLVMContext *C;
456 Type *IntptrTy;
457 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000458 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000459
460 SmallVector<AllocaInst*, 16> AllocaVec;
461 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000462 unsigned StackAlignment;
463
Kostya Serebryany6805de52013-09-10 13:16:56 +0000464 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
465 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000466 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
467
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000468 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
469 struct AllocaPoisonCall {
470 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000471 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000472 uint64_t Size;
473 bool DoPoison;
474 };
475 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
476
Yury Gribov55441bb2014-11-21 10:29:50 +0000477 // Stores left and right redzone shadow addresses for dynamic alloca
478 // and pointer to alloca instruction itself.
479 // LeftRzAddr is a shadow address for alloca left redzone.
480 // RightRzAddr is a shadow address for alloca right redzone.
481 struct DynamicAllocaCall {
482 AllocaInst *AI;
483 Value *LeftRzAddr;
484 Value *RightRzAddr;
485 explicit DynamicAllocaCall(AllocaInst *AI,
486 Value *LeftRzAddr = nullptr,
487 Value *RightRzAddr = nullptr)
488 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr)
489 {}
490 };
491 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
492
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000493 // Maps Value to an AllocaInst from which the Value is originated.
494 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
495 AllocaForValueMapTy AllocaForValue;
496
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000497 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
498 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
499 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000500 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000501 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000502
503 bool runOnFunction() {
504 if (!ClStack) return false;
505 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000506 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000507 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000508
Yury Gribov55441bb2014-11-21 10:29:50 +0000509 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000510
511 initializeCallbacks(*F.getParent());
512
513 poisonStack();
514
515 if (ClDebugStack) {
516 DEBUG(dbgs() << F);
517 }
518 return true;
519 }
520
Yury Gribov55441bb2014-11-21 10:29:50 +0000521 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000522 // poisoned red zones around all of them.
523 // Then unpoison everything back before the function returns.
524 void poisonStack();
525
526 // ----------------------- Visitors.
527 /// \brief Collect all Ret instructions.
528 void visitReturnInst(ReturnInst &RI) {
529 RetVec.push_back(&RI);
530 }
531
Yury Gribov55441bb2014-11-21 10:29:50 +0000532 // Unpoison dynamic allocas redzones.
533 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
534 for (auto Ret : RetVec) {
535 IRBuilder<> IRBRet(Ret);
536 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
537 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
538 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
539 ConstantInt::get(IntptrTy, 4));
540 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
541 Int32PtrTy));
542 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
543 Int32PtrTy));
544 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
545 Int32PtrTy));
546 }
547 }
548
549 // Right shift for BigEndian and left shift for LittleEndian.
550 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
551 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
552 : IRB.CreateLShr(Val, Shift);
553 }
554
555 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
556 // size of requested memory until runtime, we should compute it dynamically.
557 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
558 // otherwise it would contain the value that we will use to poison the
559 // partial redzone for alloca call.
560 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
561
562 // Deploy and poison redzones around dynamic alloca call. To do this, we
563 // should replace this call with another one with changed parameters and
564 // replace all its uses with new address, so
565 // addr = alloca type, old_size, align
566 // is replaced by
567 // new_size = (old_size + additional_size) * sizeof(type)
568 // tmp = alloca i8, new_size, max(align, 32)
569 // addr = tmp + 32 (first 32 bytes are for the left redzone).
570 // Additional_size is added to make new memory allocation contain not only
571 // requested memory, but also left, partial and right redzones.
572 // After that, we should poison redzones:
573 // (1) Left redzone with kAsanAllocaLeftMagic.
574 // (2) Partial redzone with the value, computed in runtime by
575 // computePartialRzMagic function.
576 // (3) Right redzone with kAsanAllocaRightMagic.
577 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
578
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000579 /// \brief Collect Alloca instructions we want (and can) handle.
580 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000581 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000582
583 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000584 if (isDynamicAlloca(AI))
585 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
586 else
587 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000588 }
589
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000590 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
591 /// errors.
592 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000593 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000594 Intrinsic::ID ID = II.getIntrinsicID();
595 if (ID != Intrinsic::lifetime_start &&
596 ID != Intrinsic::lifetime_end)
597 return;
598 // Found lifetime intrinsic, add ASan instrumentation if necessary.
599 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
600 // If size argument is undefined, don't do anything.
601 if (Size->isMinusOne()) return;
602 // Check that size doesn't saturate uint64_t and can
603 // be stored in IntptrTy.
604 const uint64_t SizeValue = Size->getValue().getLimitedValue();
605 if (SizeValue == ~0ULL ||
606 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
607 return;
608 // Find alloca instruction that corresponds to llvm.lifetime argument.
609 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
610 if (!AI) return;
611 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000612 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000613 AllocaPoisonCallVec.push_back(APC);
614 }
615
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000616 // ---------------------- Helpers.
617 void initializeCallbacks(Module &M);
618
Yury Gribov55441bb2014-11-21 10:29:50 +0000619 bool isDynamicAlloca(AllocaInst &AI) const {
620 return AI.isArrayAllocation() || !AI.isStaticAlloca();
621 }
622
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000623 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000624 bool isInterestingAlloca(AllocaInst &AI) const {
Yury Gribov55441bb2014-11-21 10:29:50 +0000625 return (AI.getAllocatedType()->isSized() &&
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000626 // alloca() may be called with 0 size, ignore it.
627 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000628 }
629
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000630 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000631 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000632 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000633 return SizeInBytes;
634 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000635 /// Finds alloca where the value comes from.
636 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000637 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000638 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000639 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000640
641 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
642 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000643};
644
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000645} // namespace
646
647char AddressSanitizer::ID = 0;
648INITIALIZE_PASS(AddressSanitizer, "asan",
649 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
650 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000651FunctionPass *llvm::createAddressSanitizerFunctionPass() {
652 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000653}
654
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000655char AddressSanitizerModule::ID = 0;
656INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
657 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
658 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000659ModulePass *llvm::createAddressSanitizerModulePass() {
660 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000661}
662
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000663static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000664 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000665 assert(Res < kNumberOfAccessSizes);
666 return Res;
667}
668
Bill Wendling58f8cef2013-08-06 22:52:42 +0000669// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000670static GlobalVariable *createPrivateGlobalForString(
671 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000672 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000673 // We use private linkage for module-local strings. If they can be merged
674 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000675 GlobalVariable *GV =
676 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000677 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
678 if (AllowMerging)
679 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000680 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
681 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000682}
683
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000684/// \brief Create a global describing a source location.
685static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
686 LocationMetadata MD) {
687 Constant *LocData[] = {
688 createPrivateGlobalForString(M, MD.Filename, true),
689 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
690 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
691 };
692 auto LocStruct = ConstantStruct::getAnon(LocData);
693 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
694 GlobalValue::PrivateLinkage, LocStruct,
695 kAsanGenPrefix);
696 GV->setUnnamedAddr(true);
697 return GV;
698}
699
Kostya Serebryany139a9372012-11-20 14:16:08 +0000700static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000701 return G->getName().find(kAsanGenPrefix) == 0 ||
702 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000703}
704
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000705Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
706 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000707 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
708 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000709 return Shadow;
710 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000711 if (Mapping.OrShadowOffset)
712 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
713 else
714 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000715}
716
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000717// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000718void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
719 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000720 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000721 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000722 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
723 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
724 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
725 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
726 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000727 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000728 AsanMemset,
729 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
730 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
731 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000732 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000733 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000734}
735
Kostya Serebryany90241602012-05-30 09:04:06 +0000736// If I is an interesting memory access, return the PointerOperand
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000737// and set IsWrite/Alignment. Otherwise return nullptr.
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000738static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
739 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000740 // Skip memory accesses inserted by another instrumentation.
741 if (I->getMetadata("nosanitize"))
742 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000743 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000744 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000745 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000746 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000747 return LI->getPointerOperand();
748 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000749 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000750 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000751 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000752 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000753 return SI->getPointerOperand();
754 }
755 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000756 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000757 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000758 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000759 return RMW->getPointerOperand();
760 }
761 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000762 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000763 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000764 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000765 return XCHG->getPointerOperand();
766 }
Craig Topperf40110f2014-04-25 05:29:35 +0000767 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000768}
769
Kostya Serebryany796f6552014-02-27 12:45:36 +0000770static bool isPointerOperand(Value *V) {
771 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
772}
773
774// This is a rough heuristic; it may cause both false positives and
775// false negatives. The proper implementation requires cooperation with
776// the frontend.
777static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
778 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
779 if (!Cmp->isRelational())
780 return false;
781 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000782 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000783 return false;
784 } else {
785 return false;
786 }
787 if (!isPointerOperand(I->getOperand(0)) ||
788 !isPointerOperand(I->getOperand(1)))
789 return false;
790 return true;
791}
792
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000793bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
794 // If a global variable does not have dynamic initialization we don't
795 // have to instrument it. However, if a global does not have initializer
796 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000797 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000798}
799
Kostya Serebryany796f6552014-02-27 12:45:36 +0000800void
801AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
802 IRBuilder<> IRB(I);
803 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
804 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
805 for (int i = 0; i < 2; i++) {
806 if (Param[i]->getType()->isPointerTy())
807 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
808 }
809 IRB.CreateCall2(F, Param[0], Param[1]);
810}
811
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000812void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000813 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000814 unsigned Alignment = 0;
815 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000816 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000817 if (ClOpt && ClOptGlobals) {
818 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
819 // If initialization order checking is disabled, a simple access to a
820 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000821 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000822 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000823 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000824 }
825 }
826 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
827 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
828 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
829 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
830 NumOptimizedAccessesToGlobalArray++;
831 return;
832 }
833 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000834 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000835 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000836
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000837 Type *OrigPtrTy = Addr->getType();
838 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
839
840 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000841 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000842
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000843 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000844
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000845 if (IsWrite)
846 NumInstrumentedWrites++;
847 else
848 NumInstrumentedReads++;
849
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000850 unsigned Granularity = 1 << Mapping.Scale;
851 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
852 // if the data is properly aligned.
853 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
854 TypeSize == 128) &&
855 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000856 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000857 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000858 // We can not do it with a single check, so we do 1-byte check for the first
859 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
860 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000861 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000862 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000863 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
864 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000865 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000866 } else {
867 Value *LastByte = IRB.CreateIntToPtr(
868 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
869 OrigPtrTy);
870 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
871 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
872 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000873}
874
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000875// Validate the result of Module::getOrInsertFunction called for an interface
876// function of AddressSanitizer. If the instrumented module defines a function
877// with the same name, their prototypes must match, otherwise
878// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000879static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000880 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
881 FuncOrBitcast->dump();
882 report_fatal_error("trying to redefine an AddressSanitizer "
883 "interface function");
884}
885
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000886Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000887 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000888 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000889 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000890 CallInst *Call = SizeArgument
891 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
892 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
893
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000894 // We don't do Call->setDoesNotReturn() because the BB already has
895 // UnreachableInst at the end.
896 // This EmptyAsm is required to avoid callback merge.
897 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000898 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000899}
900
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000901Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000902 Value *ShadowValue,
903 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000904 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000905 // Addr & (Granularity - 1)
906 Value *LastAccessedByte = IRB.CreateAnd(
907 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
908 // (Addr & (Granularity - 1)) + size - 1
909 if (TypeSize / 8 > 1)
910 LastAccessedByte = IRB.CreateAdd(
911 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
912 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
913 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000914 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000915 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
916 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
917}
918
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000919void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000920 Instruction *InsertBefore, Value *Addr,
921 uint32_t TypeSize, bool IsWrite,
922 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000923 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000924 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000925 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
926
927 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000928 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
929 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000930 return;
931 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000932
933 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000934 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000935 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
936 Value *ShadowPtr = memToShadow(AddrLong, IRB);
937 Value *CmpVal = Constant::getNullValue(ShadowTy);
938 Value *ShadowValue = IRB.CreateLoad(
939 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
940
941 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000942 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000943 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000944
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000945 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000946 // We use branch weights for the slow path check, to indicate that the slow
947 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000948 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000949 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
950 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000951 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000952 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000953 IRB.SetInsertPoint(CheckTerm);
954 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000955 BasicBlock *CrashBlock =
956 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000957 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000958 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
959 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000960 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000961 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000962 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000963
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000964 Instruction *Crash = generateCrashCode(
965 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000966 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000967}
968
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000969void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
970 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000971 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000972 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000973
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000974 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000975 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
976 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000977
978 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000979 for (auto &BB : GlobalInit.getBasicBlockList())
980 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000981 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000982}
983
984void AddressSanitizerModule::createInitializerPoisonCalls(
985 Module &M, GlobalValue *ModuleName) {
986 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
987
988 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
989 for (Use &OP : CA->operands()) {
990 if (isa<ConstantAggregateZero>(OP))
991 continue;
992 ConstantStruct *CS = cast<ConstantStruct>(OP);
993
994 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000995 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +0000996 if (F->getName() == kAsanModuleCtorName) continue;
997 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
998 // Don't instrument CTORs that will run before asan.module_ctor.
999 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1000 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001001 }
1002 }
1003}
1004
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001005bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001006 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001007 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001008
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001009 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001010 if (!Ty->isSized()) return false;
1011 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001012 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001013 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001014 // Don't handle ODR linkage types and COMDATs since other modules may be built
1015 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001016 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1017 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1018 G->getLinkage() != GlobalVariable::InternalLinkage)
1019 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001020 if (G->hasComdat())
1021 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001022 // Two problems with thread-locals:
1023 // - The address of the main thread's copy can't be computed at link-time.
1024 // - Need to poison all copies, not just the main thread's one.
1025 if (G->isThreadLocal())
1026 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001027 // For now, just ignore this Global if the alignment is large.
1028 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001029
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001030 if (G->hasSection()) {
1031 StringRef Section(G->getSection());
1032 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1033 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1034 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001035 if (Section.startswith("__OBJC,") ||
1036 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +00001037 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001038 return false;
1039 }
1040 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1041 // Constant CFString instances are compiled in the following way:
1042 // -- the string buffer is emitted into
1043 // __TEXT,__cstring,cstring_literals
1044 // -- the constant NSConstantString structure referencing that buffer
1045 // is placed into __DATA,__cfstring
1046 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1047 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001048 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +00001049 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1050 return false;
1051 }
1052 // The linker merges the contents of cstring_literals and removes the
1053 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001054 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +00001055 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001056 return false;
1057 }
Rafael Espindolab7a45052014-11-06 20:01:34 +00001058 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
1059 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
1060 return false;
1061 }
1062
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001063
1064 // Callbacks put into the CRT initializer/terminator sections
1065 // should not be instrumented.
1066 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1067 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1068 if (Section.startswith(".CRT")) {
1069 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1070 return false;
1071 }
1072
Alexander Potapenko04969e82014-03-20 10:48:34 +00001073 // Globals from llvm.metadata aren't emitted, do not instrument them.
1074 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001075 }
1076
1077 return true;
1078}
1079
Alexey Samsonov788381b2012-12-25 12:28:20 +00001080void AddressSanitizerModule::initializeCallbacks(Module &M) {
1081 IRBuilder<> IRB(*C);
1082 // Declare our poisoning and unpoisoning functions.
1083 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001084 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001085 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1086 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001087 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001088 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1089 // Declare functions that register/unregister globals.
1090 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1091 kAsanRegisterGlobalsName, IRB.getVoidTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001092 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001093 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1094 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1095 kAsanUnregisterGlobalsName,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001096 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001097 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1098}
1099
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001100// This function replaces all global variables with new variables that have
1101// trailing redzones. It also creates a function that poisons
1102// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001103bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001104 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001105
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001106 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1107
Alexey Samsonova02e6642014-05-29 18:40:48 +00001108 for (auto &G : M.globals()) {
1109 if (ShouldInstrumentGlobal(&G))
1110 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001111 }
1112
1113 size_t n = GlobalsToChange.size();
1114 if (n == 0) return false;
1115
1116 // A global is described by a structure
1117 // size_t beg;
1118 // size_t size;
1119 // size_t size_with_redzone;
1120 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001121 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001122 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001123 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001124 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001125 StructType *GlobalStructTy =
1126 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001127 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001128 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001129
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001130 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001131
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001132 // We shouldn't merge same module names, as this string serves as unique
1133 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001134 GlobalVariable *ModuleName = createPrivateGlobalForString(
1135 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001136
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001137 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001138 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001139 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001140
1141 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001142 // Create string holding the global name (use global name from metadata
1143 // if it's available, otherwise just write the name of global variable).
1144 GlobalVariable *Name = createPrivateGlobalForString(
1145 M, MD.Name.empty() ? G->getName() : MD.Name,
1146 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001147
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001148 PointerType *PtrTy = cast<PointerType>(G->getType());
1149 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001150 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001151 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001152 // MinRZ <= RZ <= kMaxGlobalRedzone
1153 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001154 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001155 std::min(kMaxGlobalRedzone,
1156 (SizeInBytes / MinRZ / 4) * MinRZ));
1157 uint64_t RightRedzoneSize = RZ;
1158 // Round up to MinRZ
1159 if (SizeInBytes % MinRZ)
1160 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1161 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001162 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1163
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001164 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001165 Constant *NewInitializer = ConstantStruct::get(
1166 NewTy, G->getInitializer(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001167 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001168
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001169 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001170 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1171 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1172 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001173 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001174 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001175 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001176 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001177 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001178
1179 Value *Indices2[2];
1180 Indices2[0] = IRB.getInt32(0);
1181 Indices2[1] = IRB.getInt32(0);
1182
1183 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001184 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001185 NewGlobal->takeName(G);
1186 G->eraseFromParent();
1187
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001188 Constant *SourceLoc;
1189 if (!MD.SourceLoc.empty()) {
1190 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1191 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1192 } else {
1193 SourceLoc = ConstantInt::get(IntptrTy, 0);
1194 }
1195
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001196 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001197 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001198 ConstantInt::get(IntptrTy, SizeInBytes),
1199 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1200 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001201 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001202 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001203
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001204 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001205 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001206
Kostya Serebryany20343352012-10-17 13:40:06 +00001207 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001208 }
1209
1210 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1211 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001212 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001213 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1214
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001215 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001216 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001217 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001218 IRB.CreateCall2(AsanRegisterGlobals,
1219 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1220 ConstantInt::get(IntptrTy, n));
1221
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001222 // We also need to unregister globals at the end, e.g. when a shared library
1223 // gets closed.
1224 Function *AsanDtorFunction = Function::Create(
1225 FunctionType::get(Type::getVoidTy(*C), false),
1226 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1227 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1228 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001229 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1230 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1231 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001232 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001233
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001234 DEBUG(dbgs() << M);
1235 return true;
1236}
1237
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001238bool AddressSanitizerModule::runOnModule(Module &M) {
1239 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1240 if (!DLP)
1241 return false;
1242 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001243 C = &(M.getContext());
1244 int LongSize = DL->getPointerSizeInBits();
1245 IntptrTy = Type::getIntNTy(*C, LongSize);
1246 Mapping = getShadowMapping(M, LongSize);
1247 initializeCallbacks(M);
1248
1249 bool Changed = false;
1250
1251 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1252 assert(CtorFunc);
1253 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1254
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001255 if (ClGlobals)
1256 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001257
1258 return Changed;
1259}
1260
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001261void AddressSanitizer::initializeCallbacks(Module &M) {
1262 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001263 // Create __asan_report* callbacks.
1264 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1265 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1266 AccessSizeIndex++) {
1267 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001268 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001269 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001270 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001271 checkInterfaceFunction(
1272 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001273 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001274 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1275 checkInterfaceFunction(
1276 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001277 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001278 }
1279 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001280 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001281 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001282 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001283 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001284
Kostya Serebryany86332c02014-04-21 07:10:43 +00001285 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1286 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001287 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001288 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1289 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001290 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001291
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001292 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1293 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001294 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001295 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1296 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001297 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001298 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1299 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001300 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001301
1302 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001303 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001304
Kostya Serebryany796f6552014-02-27 12:45:36 +00001305 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001306 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001307 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001308 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001309 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1310 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1311 StringRef(""), StringRef(""),
1312 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001313}
1314
1315// virtual
1316bool AddressSanitizer::doInitialization(Module &M) {
1317 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001318 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1319 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001320 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001321 DL = &DLP->getDataLayout();
1322
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001323 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001324
1325 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001326 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001327 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001328
1329 AsanCtorFunction = Function::Create(
1330 FunctionType::get(Type::getVoidTy(*C), false),
1331 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1332 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1333 // call __asan_init in the module ctor.
1334 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1335 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001336 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001337 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1338 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001339
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001340 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001341
Alexey Samsonov1f647502014-05-29 01:10:14 +00001342 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001343 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001344}
1345
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001346bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1347 // For each NSObject descendant having a +load method, this method is invoked
1348 // by the ObjC runtime before any of the static constructors is called.
1349 // Therefore we need to instrument such methods with a call to __asan_init
1350 // at the beginning in order to initialize our runtime before any access to
1351 // the shadow memory.
1352 // We cannot just ignore these methods, because they may call other
1353 // instrumented functions.
1354 if (F.getName().find(" load]") != std::string::npos) {
1355 IRBuilder<> IRB(F.begin()->begin());
1356 IRB.CreateCall(AsanInitFunction);
1357 return true;
1358 }
1359 return false;
1360}
1361
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001362bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001363 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001364 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001365 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001366 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001367
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001368 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001369 maybeInsertAsanInitAtFunctionEntry(F);
1370
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001371 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001372 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001373
1374 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1375 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001376
1377 // We want to instrument every address only once per basic block (unless there
1378 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001379 SmallSet<Value*, 16> TempsToInstrument;
1380 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001381 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001382 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001383 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001384 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001385 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001386 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001387
1388 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001389 for (auto &BB : F) {
1390 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001391 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001392 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001393 for (auto &Inst : BB) {
1394 if (LooksLikeCodeInBug11395(&Inst)) return false;
1395 if (Value *Addr =
1396 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001397 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001398 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001399 continue; // We've seen this temp in the current BB.
1400 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001401 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001402 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1403 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001404 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001405 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001406 // ok, take it.
1407 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001408 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001409 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001410 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001411 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001412 // A call inside BB.
1413 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001414 if (CS.doesNotReturn())
1415 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001416 }
1417 continue;
1418 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001419 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001420 NumInsnsPerBB++;
1421 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1422 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001423 }
1424 }
1425
Craig Topperf40110f2014-04-25 05:29:35 +00001426 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001427 bool LikelyToInstrument =
1428 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1429 if (ClKeepUninstrumented && LikelyToInstrument) {
1430 ValueToValueMapTy VMap;
1431 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1432 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1433 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1434 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1435 }
1436
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001437 bool UseCalls = false;
1438 if (ClInstrumentationWithCallsThreshold >= 0 &&
1439 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1440 UseCalls = true;
1441
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001442 // Instrument.
1443 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001444 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001445 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1446 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001447 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001448 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001449 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001450 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001451 }
1452 NumInstrumented++;
1453 }
1454
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001455 FunctionStackPoisoner FSP(F, *this);
1456 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001457
1458 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1459 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001460 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001461 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001462 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001463 }
1464
Alexey Samsonova02e6642014-05-29 18:40:48 +00001465 for (auto Inst : PointerComparisonsOrSubtracts) {
1466 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001467 NumInstrumented++;
1468 }
1469
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001470 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001471
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001472 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1473
1474 if (ClKeepUninstrumented) {
1475 if (!res) {
1476 // No instrumentation is done, no need for the duplicate.
1477 if (UninstrumentedDuplicate)
1478 UninstrumentedDuplicate->eraseFromParent();
1479 } else {
1480 // The function was instrumented. We must have the duplicate.
1481 assert(UninstrumentedDuplicate);
1482 UninstrumentedDuplicate->setSection("NOASAN");
1483 assert(!F.hasSection());
1484 F.setSection("ASAN");
1485 }
1486 }
1487
1488 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001489}
1490
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001491// Workaround for bug 11395: we don't want to instrument stack in functions
1492// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1493// FIXME: remove once the bug 11395 is fixed.
1494bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1495 if (LongSize != 32) return false;
1496 CallInst *CI = dyn_cast<CallInst>(I);
1497 if (!CI || !CI->isInlineAsm()) return false;
1498 if (CI->getNumArgOperands() <= 5) return false;
1499 // We have inline assembly with quite a few arguments.
1500 return true;
1501}
1502
1503void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1504 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001505 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1506 std::string Suffix = itostr(i);
1507 AsanStackMallocFunc[i] = checkInterfaceFunction(
1508 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001509 IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001510 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1511 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001512 IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001513 }
David Blaikiea92765c2014-11-14 00:41:42 +00001514 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1515 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1516 IntptrTy, IntptrTy, nullptr));
1517 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1518 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1519 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001520}
1521
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001522void
Craig Topper3af97222014-08-27 05:25:00 +00001523FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001524 IRBuilder<> &IRB, Value *ShadowBase,
1525 bool DoPoison) {
1526 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001527 size_t i = 0;
1528 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1529 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1530 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1531 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1532 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1533 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1534 uint64_t Val = 0;
1535 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001536 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001537 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1538 else
1539 Val = (Val << 8) | ShadowBytes[i + j];
1540 }
1541 if (!Val) continue;
1542 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1543 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1544 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1545 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001546 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001547 }
1548}
1549
Kostya Serebryany6805de52013-09-10 13:16:56 +00001550// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1551// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1552static int StackMallocSizeClass(uint64_t LocalStackSize) {
1553 assert(LocalStackSize <= kMaxStackMallocSize);
1554 uint64_t MaxSize = kMinStackMallocSize;
1555 for (int i = 0; ; i++, MaxSize *= 2)
1556 if (LocalStackSize <= MaxSize)
1557 return i;
1558 llvm_unreachable("impossible LocalStackSize");
1559}
1560
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001561// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1562// We can not use MemSet intrinsic because it may end up calling the actual
1563// memset. Size is a multiple of 8.
1564// Currently this generates 8-byte stores on x86_64; it may be better to
1565// generate wider stores.
1566void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1567 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1568 assert(!(Size % 8));
1569 assert(kAsanStackAfterReturnMagic == 0xf5);
1570 for (int i = 0; i < Size; i += 8) {
1571 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1572 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1573 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1574 }
1575}
1576
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001577static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001578 for (const auto &Inst : F.getEntryBlock())
1579 if (!isa<AllocaInst>(Inst))
1580 return Inst.getDebugLoc();
1581 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001582}
1583
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001584void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001585 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1586
1587 if (ClInstrumentAllocas)
1588 // Handle dynamic allocas.
1589 for (auto &AllocaCall : DynamicAllocaVec)
1590 handleDynamicAllocaCall(AllocaCall);
1591
1592 if (AllocaVec.size() == 0) return;
1593
Kostya Serebryany6805de52013-09-10 13:16:56 +00001594 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001595 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001596
1597 Instruction *InsBefore = AllocaVec[0];
1598 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001599 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001600
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001601 SmallVector<ASanStackVariableDescription, 16> SVD;
1602 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001603 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001604 ASanStackVariableDescription D = { AI->getName().data(),
1605 getAllocaSizeInBytes(AI),
1606 AI->getAlignment(), AI, 0};
1607 SVD.push_back(D);
1608 }
1609 // Minimal header size (left redzone) is 4 pointers,
1610 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1611 size_t MinHeaderSize = ASan.LongSize / 2;
1612 ASanStackFrameLayout L;
1613 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1614 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1615 uint64_t LocalStackSize = L.FrameSize;
1616 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001617 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001618
1619 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1620 AllocaInst *MyAlloca =
1621 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001622 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001623 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1624 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1625 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001626 assert(MyAlloca->isStaticAlloca());
1627 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1628 Value *LocalStackBase = OrigStackBase;
1629
1630 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001631 // LocalStackBase = OrigStackBase
1632 // if (__asan_option_detect_stack_use_after_return)
1633 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001634 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1635 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001636 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1637 kAsanOptionDetectUAR, IRB.getInt32Ty());
1638 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1639 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001640 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001641 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1642 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001643 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001644 LocalStackBase = IRBIf.CreateCall2(
1645 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001646 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001647 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1648 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001649 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001650 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1651 Phi->addIncoming(OrigStackBase, CmpBlock);
1652 Phi->addIncoming(LocalStackBase, SetBlock);
1653 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001654 }
1655
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001656 // Insert poison calls for lifetime intrinsics for alloca.
1657 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001658 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001659 assert(APC.InsBefore);
1660 assert(APC.AI);
1661 IRBuilder<> IRB(APC.InsBefore);
1662 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001663 HavePoisonedAllocas |= APC.DoPoison;
1664 }
1665
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001666 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001667 for (const auto &Desc : SVD) {
1668 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001669 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001670 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001671 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001672 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001673 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001674 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001675
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001676 // The left-most redzone has enough space for at least 4 pointers.
1677 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001678 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1679 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1680 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001681 // Write the frame description constant to redzone[1].
1682 Value *BasePlus1 = IRB.CreateIntToPtr(
1683 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1684 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001685 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001686 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1687 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001688 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1689 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001690 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001691 // Write the PC to redzone[2].
1692 Value *BasePlus2 = IRB.CreateIntToPtr(
1693 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1694 2 * ASan.LongSize/8)),
1695 IntptrPtrTy);
1696 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001697
1698 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001699 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001700 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001701
Kostya Serebryany530e2072013-12-23 14:15:08 +00001702 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001703 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001704 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001705 // Mark the current frame as retired.
1706 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1707 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001708 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001709 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001710 // if LocalStackBase != OrigStackBase:
1711 // // In use-after-return mode, poison the whole stack frame.
1712 // if StackMallocIdx <= 4
1713 // // For small sizes inline the whole thing:
1714 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1715 // **SavedFlagPtr(LocalStackBase) = 0
1716 // else
1717 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1718 // else
1719 // <This is not a fake stack; unpoison the redzones>
1720 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1721 TerminatorInst *ThenTerm, *ElseTerm;
1722 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1723
1724 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001725 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001726 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1727 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1728 ClassSize >> Mapping.Scale);
1729 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1730 LocalStackBase,
1731 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1732 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1733 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1734 IRBPoison.CreateStore(
1735 Constant::getNullValue(IRBPoison.getInt8Ty()),
1736 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1737 } else {
1738 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001739 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1740 ConstantInt::get(IntptrTy, LocalStackSize),
1741 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001742 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001743
1744 IRBuilder<> IRBElse(ElseTerm);
1745 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001746 } else if (HavePoisonedAllocas) {
1747 // If we poisoned some allocas in llvm.lifetime analysis,
1748 // unpoison whole stack frame now.
1749 assert(LocalStackBase == OrigStackBase);
1750 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001751 } else {
1752 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001753 }
1754 }
1755
Yury Gribov55441bb2014-11-21 10:29:50 +00001756 if (ClInstrumentAllocas)
1757 // Unpoison dynamic allocas.
1758 for (auto &AllocaCall : DynamicAllocaVec)
1759 unpoisonDynamicAlloca(AllocaCall);
1760
Kostya Serebryany09959942012-10-19 06:20:53 +00001761 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001762 for (auto AI : AllocaVec)
1763 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001764}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001765
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001766void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001767 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001768 // For now just insert the call to ASan runtime.
1769 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1770 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1771 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1772 : AsanUnpoisonStackMemoryFunc,
1773 AddrArg, SizeArg);
1774}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001775
1776// Handling llvm.lifetime intrinsics for a given %alloca:
1777// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1778// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1779// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1780// could be poisoned by previous llvm.lifetime.end instruction, as the
1781// variable may go in and out of scope several times, e.g. in loops).
1782// (3) if we poisoned at least one %alloca in a function,
1783// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001784
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001785AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1786 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1787 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001788 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001789 // See if we've already calculated (or started to calculate) alloca for a
1790 // given value.
1791 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1792 if (I != AllocaForValue.end())
1793 return I->second;
1794 // Store 0 while we're calculating alloca for value V to avoid
1795 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001796 AllocaForValue[V] = nullptr;
1797 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001798 if (CastInst *CI = dyn_cast<CastInst>(V))
1799 Res = findAllocaForValue(CI->getOperand(0));
1800 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1801 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1802 Value *IncValue = PN->getIncomingValue(i);
1803 // Allow self-referencing phi-nodes.
1804 if (IncValue == PN) continue;
1805 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1806 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001807 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1808 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001809 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001810 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001811 }
Craig Topperf40110f2014-04-25 05:29:35 +00001812 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001813 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001814 return Res;
1815}
Yury Gribov55441bb2014-11-21 10:29:50 +00001816
1817// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1818// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1819// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1820// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1821// 8-byte chunk of user memory respectively.
1822// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1823// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1824
1825// Shift = Padding & ~7; // the number of bits we need to shift to access first
1826// chunk in shadow memory, containing nonzero bytes.
1827// Example:
1828// Padding = 21 Padding = 16
1829// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1830// ^ ^
1831// | |
1832// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1833//
1834// Val1 = 0xcbcbcbcb << Shift;
1835// PartialBits = Padding ? Padding & 7 : 0xcb;
1836// Val2 = PartialBits << Shift;
1837// Result = Val1 | Val2;
1838Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1839 IRBuilder<> &IRB) {
1840 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1841 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1842 unsigned Val1Int = kAsanAllocaPartialVal1;
1843 unsigned Val2Int = kAsanAllocaPartialVal2;
1844 if (!ASan.DL->isLittleEndian()) {
1845 Val1Int = sys::getSwappedBytes(Val1Int);
1846 Val2Int = sys::getSwappedBytes(Val2Int);
1847 }
1848 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1849 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1850 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1851 if (ASan.DL->isBigEndian())
1852 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1853 Value *Val2 = IRB.getInt32(Val2Int);
1854 Value *Cond =
1855 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1856 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1857 shiftAllocaMagic(Val2, IRB, Shift));
1858 return IRB.CreateOr(Val1, Val2);
1859}
1860
1861void FunctionStackPoisoner::handleDynamicAllocaCall(
1862 DynamicAllocaCall &AllocaCall) {
1863 AllocaInst *AI = AllocaCall.AI;
1864 IRBuilder<> IRB(AI);
1865
1866 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1867 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1868 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1869
1870 Value *Zero = Constant::getNullValue(IntptrTy);
1871 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1872 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1873 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1874
1875 // Since we need to extend alloca with additional memory to locate
1876 // redzones, and OldSize is number of allocated blocks with
1877 // ElementSize size, get allocated memory size in bytes by
1878 // OldSize * ElementSize.
1879 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1880 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1881 ConstantInt::get(IntptrTy, ElementSize));
1882
1883 // PartialSize = OldSize % 32
1884 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1885
1886 // Misalign = kAllocaRzSize - PartialSize;
1887 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1888
1889 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1890 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1891 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1892
1893 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1894 // Align is added to locate left redzone, PartialPadding for possible
1895 // partial redzone and kAllocaRzSize for right redzone respectively.
1896 Value *AdditionalChunkSize = IRB.CreateAdd(
1897 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1898
1899 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1900
1901 // Insert new alloca with new NewSize and Align params.
1902 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1903 NewAlloca->setAlignment(Align);
1904
1905 // NewAddress = Address + Align
1906 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1907 ConstantInt::get(IntptrTy, Align));
1908
1909 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1910
1911 // LeftRzAddress = NewAddress - kAllocaRzSize
1912 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1913
1914 // Poisoning left redzone.
1915 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1916 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1917 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1918
1919 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1920 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
1921 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
1922
1923 // Poisoning partial redzone.
1924 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
1925 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
1926 IRB.CreateStore(PartialRzMagic,
1927 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
1928
1929 // RightRzAddress
1930 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
1931 Value *RightRzAddress = IRB.CreateAnd(
1932 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
1933
1934 // Poisoning right redzone.
1935 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
1936 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
1937 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
1938
1939 // Replace all uses of AddessReturnedByAlloca with NewAddress.
1940 AI->replaceAllUsesWith(NewAddressPtr);
1941
1942 // We are done. Erase old alloca and store left, partial and right redzones
1943 // shadow addresses for future unpoisoning.
1944 AI->eraseFromParent();
1945}