blob: 414fb65d6636c15382ad2ed9f65e5f6468bb10c0 [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");
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +0000212STATISTIC(NumInstrumentedDynamicAllocas,
213 "Number of instrumented dynamic allocas");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000214STATISTIC(NumOptimizedAccessesToGlobalArray,
215 "Number of optimized accesses to global arrays");
216STATISTIC(NumOptimizedAccessesToGlobalVar,
217 "Number of optimized accesses to global vars");
218
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000219namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000220/// Frontend-provided metadata for source location.
221struct LocationMetadata {
222 StringRef Filename;
223 int LineNo;
224 int ColumnNo;
225
226 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
227
228 bool empty() const { return Filename.empty(); }
229
230 void parse(MDNode *MDN) {
231 assert(MDN->getNumOperands() == 3);
232 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
233 Filename = MDFilename->getString();
234 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
235 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
236 }
237};
238
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000239/// Frontend-provided metadata for global variables.
240class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000241 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000242 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000243 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000244 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000245 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000246 LocationMetadata SourceLoc;
247 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000248 bool IsDynInit;
249 bool IsBlacklisted;
250 };
251
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000252 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000253
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000254 void init(Module& M) {
255 assert(!inited_);
256 inited_ = true;
257 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
258 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000259 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000260 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000261 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000262 assert(MDN->getNumOperands() == 5);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000263 Value *V = MDN->getOperand(0);
264 // The optimizer may optimize away a global entirely.
265 if (!V)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000266 continue;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000267 GlobalVariable *GV = cast<GlobalVariable>(V);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000268 // We can already have an entry for GV if it was merged with another
269 // global.
270 Entry &E = Entries[GV];
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000271 if (Value *Loc = MDN->getOperand(1))
272 E.SourceLoc.parse(cast<MDNode>(Loc));
Alexey Samsonov15c96692014-07-12 00:42:52 +0000273 if (Value *Name = MDN->getOperand(2)) {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000274 MDString *MDName = cast<MDString>(Name);
275 E.Name = MDName->getString();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000276 }
277 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000278 E.IsDynInit |= IsDynInit->isOne();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000279 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000280 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000281 }
282 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000283
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000284 /// Returns metadata entry for a given global.
285 Entry get(GlobalVariable *G) const {
286 auto Pos = Entries.find(G);
287 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000288 }
289
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000290 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000291 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000292 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000293};
294
Alexey Samsonov1345d352013-01-16 13:23:28 +0000295/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000296/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000297struct ShadowMapping {
298 int Scale;
299 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000300 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000301};
302
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000303static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000304 llvm::Triple TargetTriple(M.getTargetTriple());
305 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000306 bool IsIOS = TargetTriple.isiOS();
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000307 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000308 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000309 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
310 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000311 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000312 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
313 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000314 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
315 TargetTriple.getArch() == llvm::Triple::mips64el;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000316
317 ShadowMapping Mapping;
318
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000319 if (LongSize == 32) {
320 if (IsAndroid)
321 Mapping.Offset = 0;
322 else if (IsMIPS32)
323 Mapping.Offset = kMIPS32_ShadowOffset32;
324 else if (IsFreeBSD)
325 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000326 else if (IsIOS)
327 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000328 else
329 Mapping.Offset = kDefaultShadowOffset32;
330 } else { // LongSize == 64
331 if (IsPPC64)
332 Mapping.Offset = kPPC64_ShadowOffset64;
333 else if (IsFreeBSD)
334 Mapping.Offset = kFreeBSD_ShadowOffset64;
335 else if (IsLinux && IsX86_64)
336 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000337 else if (IsMIPS64)
338 Mapping.Offset = kMIPS64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000339 else
340 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000341 }
342
343 Mapping.Scale = kDefaultShadowScale;
344 if (ClMappingScale) {
345 Mapping.Scale = ClMappingScale;
346 }
347
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000348 // OR-ing shadow offset if more efficient (at least on x86) if the offset
349 // is a power of two, but on ppc64 we have to use add since the shadow
350 // offset is not necessary 1/8-th of the address space.
351 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
352
Alexey Samsonov1345d352013-01-16 13:23:28 +0000353 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000354}
355
Alexey Samsonov1345d352013-01-16 13:23:28 +0000356static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000357 // Redzone used for stack and globals is at least 32 bytes.
358 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000359 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000360}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000361
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000362/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000363struct AddressSanitizer : public FunctionPass {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000364 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000365 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000366 return "AddressSanitizerFunctionPass";
367 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000368 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000369 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000370 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
371 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000372 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000373 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
374 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000375 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000376 bool IsWrite, size_t AccessSizeIndex,
377 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000378 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000379 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000380 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000381 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000382 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000383 static char ID; // Pass identification, replacement for typeid
384
385 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000386 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000387
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000388 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000389 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000390
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000391 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000392 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000393 int LongSize;
394 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000395 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000396 Function *AsanCtorFunction;
397 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000398 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000399 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000400 // This array is indexed by AccessIsWrite and log2(AccessSize).
401 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000402 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000403 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000404 Function *AsanErrorCallbackSized[2],
405 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000406 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000407 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000408 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000409
410 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000411};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000412
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000413class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000414 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000415 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000416 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000417 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000418 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000419 return "AddressSanitizerModule";
420 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000421
Kostya Serebryany20a79972012-11-22 03:18:50 +0000422 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000423 void initializeCallbacks(Module &M);
424
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000425 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000426 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000427 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000428 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000429 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000430 return RedzoneSizeForScale(Mapping.Scale);
431 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000432
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000433 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000434 Type *IntptrTy;
435 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000436 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000437 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000438 Function *AsanPoisonGlobals;
439 Function *AsanUnpoisonGlobals;
440 Function *AsanRegisterGlobals;
441 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000442};
443
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000444// Stack poisoning does not play well with exception handling.
445// When an exception is thrown, we essentially bypass the code
446// that unpoisones the stack. This is why the run-time library has
447// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
448// stack in the interceptor. This however does not work inside the
449// actual function which catches the exception. Most likely because the
450// compiler hoists the load of the shadow value somewhere too high.
451// This causes asan to report a non-existing bug on 453.povray.
452// It sounds like an LLVM bug.
453struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
454 Function &F;
455 AddressSanitizer &ASan;
456 DIBuilder DIB;
457 LLVMContext *C;
458 Type *IntptrTy;
459 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000460 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000461
462 SmallVector<AllocaInst*, 16> AllocaVec;
463 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000464 unsigned StackAlignment;
465
Kostya Serebryany6805de52013-09-10 13:16:56 +0000466 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
467 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000468 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
469
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000470 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
471 struct AllocaPoisonCall {
472 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000473 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000474 uint64_t Size;
475 bool DoPoison;
476 };
477 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
478
Yury Gribov55441bb2014-11-21 10:29:50 +0000479 // Stores left and right redzone shadow addresses for dynamic alloca
480 // and pointer to alloca instruction itself.
481 // LeftRzAddr is a shadow address for alloca left redzone.
482 // RightRzAddr is a shadow address for alloca right redzone.
483 struct DynamicAllocaCall {
484 AllocaInst *AI;
485 Value *LeftRzAddr;
486 Value *RightRzAddr;
487 explicit DynamicAllocaCall(AllocaInst *AI,
488 Value *LeftRzAddr = nullptr,
489 Value *RightRzAddr = nullptr)
490 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr)
491 {}
492 };
493 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
494
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000495 // Maps Value to an AllocaInst from which the Value is originated.
496 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
497 AllocaForValueMapTy AllocaForValue;
498
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000499 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
500 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
501 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000502 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000503 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000504
505 bool runOnFunction() {
506 if (!ClStack) return false;
507 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000508 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000509 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000510
Yury Gribov55441bb2014-11-21 10:29:50 +0000511 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000512
513 initializeCallbacks(*F.getParent());
514
515 poisonStack();
516
517 if (ClDebugStack) {
518 DEBUG(dbgs() << F);
519 }
520 return true;
521 }
522
Yury Gribov55441bb2014-11-21 10:29:50 +0000523 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000524 // poisoned red zones around all of them.
525 // Then unpoison everything back before the function returns.
526 void poisonStack();
527
528 // ----------------------- Visitors.
529 /// \brief Collect all Ret instructions.
530 void visitReturnInst(ReturnInst &RI) {
531 RetVec.push_back(&RI);
532 }
533
Yury Gribov55441bb2014-11-21 10:29:50 +0000534 // Unpoison dynamic allocas redzones.
535 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
536 for (auto Ret : RetVec) {
537 IRBuilder<> IRBRet(Ret);
538 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
539 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
540 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
541 ConstantInt::get(IntptrTy, 4));
542 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
543 Int32PtrTy));
544 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
545 Int32PtrTy));
546 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
547 Int32PtrTy));
548 }
549 }
550
551 // Right shift for BigEndian and left shift for LittleEndian.
552 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
553 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
554 : IRB.CreateLShr(Val, Shift);
555 }
556
557 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
558 // size of requested memory until runtime, we should compute it dynamically.
559 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
560 // otherwise it would contain the value that we will use to poison the
561 // partial redzone for alloca call.
562 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
563
564 // Deploy and poison redzones around dynamic alloca call. To do this, we
565 // should replace this call with another one with changed parameters and
566 // replace all its uses with new address, so
567 // addr = alloca type, old_size, align
568 // is replaced by
569 // new_size = (old_size + additional_size) * sizeof(type)
570 // tmp = alloca i8, new_size, max(align, 32)
571 // addr = tmp + 32 (first 32 bytes are for the left redzone).
572 // Additional_size is added to make new memory allocation contain not only
573 // requested memory, but also left, partial and right redzones.
574 // After that, we should poison redzones:
575 // (1) Left redzone with kAsanAllocaLeftMagic.
576 // (2) Partial redzone with the value, computed in runtime by
577 // computePartialRzMagic function.
578 // (3) Right redzone with kAsanAllocaRightMagic.
579 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
580
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000581 /// \brief Collect Alloca instructions we want (and can) handle.
582 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000583 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000584
585 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000586 if (isDynamicAlloca(AI))
587 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
588 else
589 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000590 }
591
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000592 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
593 /// errors.
594 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000595 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000596 Intrinsic::ID ID = II.getIntrinsicID();
597 if (ID != Intrinsic::lifetime_start &&
598 ID != Intrinsic::lifetime_end)
599 return;
600 // Found lifetime intrinsic, add ASan instrumentation if necessary.
601 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
602 // If size argument is undefined, don't do anything.
603 if (Size->isMinusOne()) return;
604 // Check that size doesn't saturate uint64_t and can
605 // be stored in IntptrTy.
606 const uint64_t SizeValue = Size->getValue().getLimitedValue();
607 if (SizeValue == ~0ULL ||
608 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
609 return;
610 // Find alloca instruction that corresponds to llvm.lifetime argument.
611 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
612 if (!AI) return;
613 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000614 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000615 AllocaPoisonCallVec.push_back(APC);
616 }
617
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000618 // ---------------------- Helpers.
619 void initializeCallbacks(Module &M);
620
Yury Gribov55441bb2014-11-21 10:29:50 +0000621 bool isDynamicAlloca(AllocaInst &AI) const {
622 return AI.isArrayAllocation() || !AI.isStaticAlloca();
623 }
624
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000625 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000626 bool isInterestingAlloca(AllocaInst &AI) const {
Yury Gribov55441bb2014-11-21 10:29:50 +0000627 return (AI.getAllocatedType()->isSized() &&
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000628 // alloca() may be called with 0 size, ignore it.
629 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000630 }
631
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000632 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000633 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000634 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000635 return SizeInBytes;
636 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000637 /// Finds alloca where the value comes from.
638 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000639 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000640 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000641 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000642
643 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
644 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000645};
646
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000647} // namespace
648
649char AddressSanitizer::ID = 0;
650INITIALIZE_PASS(AddressSanitizer, "asan",
651 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
652 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000653FunctionPass *llvm::createAddressSanitizerFunctionPass() {
654 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000655}
656
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000657char AddressSanitizerModule::ID = 0;
658INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
659 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
660 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000661ModulePass *llvm::createAddressSanitizerModulePass() {
662 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000663}
664
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000665static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000666 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000667 assert(Res < kNumberOfAccessSizes);
668 return Res;
669}
670
Bill Wendling58f8cef2013-08-06 22:52:42 +0000671// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000672static GlobalVariable *createPrivateGlobalForString(
673 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000674 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000675 // We use private linkage for module-local strings. If they can be merged
676 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000677 GlobalVariable *GV =
678 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000679 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
680 if (AllowMerging)
681 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000682 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
683 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000684}
685
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000686/// \brief Create a global describing a source location.
687static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
688 LocationMetadata MD) {
689 Constant *LocData[] = {
690 createPrivateGlobalForString(M, MD.Filename, true),
691 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
692 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
693 };
694 auto LocStruct = ConstantStruct::getAnon(LocData);
695 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
696 GlobalValue::PrivateLinkage, LocStruct,
697 kAsanGenPrefix);
698 GV->setUnnamedAddr(true);
699 return GV;
700}
701
Kostya Serebryany139a9372012-11-20 14:16:08 +0000702static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000703 return G->getName().find(kAsanGenPrefix) == 0 ||
704 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000705}
706
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000707Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
708 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000709 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
710 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000711 return Shadow;
712 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000713 if (Mapping.OrShadowOffset)
714 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
715 else
716 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000717}
718
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000719// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000720void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
721 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000722 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000723 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000724 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
725 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
726 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
727 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
728 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000729 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000730 AsanMemset,
731 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
732 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
733 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000734 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000735 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000736}
737
Kostya Serebryany90241602012-05-30 09:04:06 +0000738// If I is an interesting memory access, return the PointerOperand
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000739// and set IsWrite/Alignment. Otherwise return nullptr.
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000740static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
741 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000742 // Skip memory accesses inserted by another instrumentation.
743 if (I->getMetadata("nosanitize"))
744 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000745 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000746 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000747 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000748 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000749 return LI->getPointerOperand();
750 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000751 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000752 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000753 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000754 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000755 return SI->getPointerOperand();
756 }
757 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000758 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000759 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000760 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000761 return RMW->getPointerOperand();
762 }
763 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000764 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000765 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000766 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000767 return XCHG->getPointerOperand();
768 }
Craig Topperf40110f2014-04-25 05:29:35 +0000769 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000770}
771
Kostya Serebryany796f6552014-02-27 12:45:36 +0000772static bool isPointerOperand(Value *V) {
773 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
774}
775
776// This is a rough heuristic; it may cause both false positives and
777// false negatives. The proper implementation requires cooperation with
778// the frontend.
779static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
780 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
781 if (!Cmp->isRelational())
782 return false;
783 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000784 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000785 return false;
786 } else {
787 return false;
788 }
789 if (!isPointerOperand(I->getOperand(0)) ||
790 !isPointerOperand(I->getOperand(1)))
791 return false;
792 return true;
793}
794
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000795bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
796 // If a global variable does not have dynamic initialization we don't
797 // have to instrument it. However, if a global does not have initializer
798 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000799 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000800}
801
Kostya Serebryany796f6552014-02-27 12:45:36 +0000802void
803AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
804 IRBuilder<> IRB(I);
805 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
806 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
807 for (int i = 0; i < 2; i++) {
808 if (Param[i]->getType()->isPointerTy())
809 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
810 }
811 IRB.CreateCall2(F, Param[0], Param[1]);
812}
813
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000814void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000815 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000816 unsigned Alignment = 0;
817 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000818 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000819 if (ClOpt && ClOptGlobals) {
820 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
821 // If initialization order checking is disabled, a simple access to a
822 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000823 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000824 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000825 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000826 }
827 }
828 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
829 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
830 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
831 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
832 NumOptimizedAccessesToGlobalArray++;
833 return;
834 }
835 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000836 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000837 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000838
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000839 Type *OrigPtrTy = Addr->getType();
840 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
841
842 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000843 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000844
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000845 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000846
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000847 if (IsWrite)
848 NumInstrumentedWrites++;
849 else
850 NumInstrumentedReads++;
851
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000852 unsigned Granularity = 1 << Mapping.Scale;
853 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
854 // if the data is properly aligned.
855 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
856 TypeSize == 128) &&
857 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000858 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000859 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000860 // We can not do it with a single check, so we do 1-byte check for the first
861 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
862 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000863 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000864 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000865 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
866 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000867 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000868 } else {
869 Value *LastByte = IRB.CreateIntToPtr(
870 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
871 OrigPtrTy);
872 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
873 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
874 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000875}
876
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000877// Validate the result of Module::getOrInsertFunction called for an interface
878// function of AddressSanitizer. If the instrumented module defines a function
879// with the same name, their prototypes must match, otherwise
880// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000881static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000882 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
883 FuncOrBitcast->dump();
884 report_fatal_error("trying to redefine an AddressSanitizer "
885 "interface function");
886}
887
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000888Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000889 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000890 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000891 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000892 CallInst *Call = SizeArgument
893 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
894 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
895
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000896 // We don't do Call->setDoesNotReturn() because the BB already has
897 // UnreachableInst at the end.
898 // This EmptyAsm is required to avoid callback merge.
899 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000900 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000901}
902
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000903Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000904 Value *ShadowValue,
905 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000906 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000907 // Addr & (Granularity - 1)
908 Value *LastAccessedByte = IRB.CreateAnd(
909 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
910 // (Addr & (Granularity - 1)) + size - 1
911 if (TypeSize / 8 > 1)
912 LastAccessedByte = IRB.CreateAdd(
913 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
914 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
915 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000916 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000917 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
918 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
919}
920
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000921void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000922 Instruction *InsertBefore, Value *Addr,
923 uint32_t TypeSize, bool IsWrite,
924 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000925 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000926 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000927 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
928
929 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000930 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
931 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000932 return;
933 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000934
935 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000936 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000937 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
938 Value *ShadowPtr = memToShadow(AddrLong, IRB);
939 Value *CmpVal = Constant::getNullValue(ShadowTy);
940 Value *ShadowValue = IRB.CreateLoad(
941 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
942
943 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000944 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000945 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000946
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000947 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000948 // We use branch weights for the slow path check, to indicate that the slow
949 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000950 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000951 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
952 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000953 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000954 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000955 IRB.SetInsertPoint(CheckTerm);
956 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000957 BasicBlock *CrashBlock =
958 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000959 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000960 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
961 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000962 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000963 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000964 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000965
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000966 Instruction *Crash = generateCrashCode(
967 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000968 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000969}
970
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000971void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
972 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000973 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000974 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000975
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000976 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000977 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
978 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000979
980 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000981 for (auto &BB : GlobalInit.getBasicBlockList())
982 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000983 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000984}
985
986void AddressSanitizerModule::createInitializerPoisonCalls(
987 Module &M, GlobalValue *ModuleName) {
988 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
989
990 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
991 for (Use &OP : CA->operands()) {
992 if (isa<ConstantAggregateZero>(OP))
993 continue;
994 ConstantStruct *CS = cast<ConstantStruct>(OP);
995
996 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000997 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +0000998 if (F->getName() == kAsanModuleCtorName) continue;
999 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1000 // Don't instrument CTORs that will run before asan.module_ctor.
1001 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1002 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001003 }
1004 }
1005}
1006
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001007bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001008 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001009 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001010
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001011 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001012 if (!Ty->isSized()) return false;
1013 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001014 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001015 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001016 // Don't handle ODR linkage types and COMDATs since other modules may be built
1017 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001018 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1019 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1020 G->getLinkage() != GlobalVariable::InternalLinkage)
1021 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001022 if (G->hasComdat())
1023 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001024 // Two problems with thread-locals:
1025 // - The address of the main thread's copy can't be computed at link-time.
1026 // - Need to poison all copies, not just the main thread's one.
1027 if (G->isThreadLocal())
1028 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001029 // For now, just ignore this Global if the alignment is large.
1030 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001031
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001032 if (G->hasSection()) {
1033 StringRef Section(G->getSection());
1034 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1035 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1036 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001037 if (Section.startswith("__OBJC,") ||
1038 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +00001039 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001040 return false;
1041 }
1042 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1043 // Constant CFString instances are compiled in the following way:
1044 // -- the string buffer is emitted into
1045 // __TEXT,__cstring,cstring_literals
1046 // -- the constant NSConstantString structure referencing that buffer
1047 // is placed into __DATA,__cfstring
1048 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1049 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001050 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +00001051 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1052 return false;
1053 }
1054 // The linker merges the contents of cstring_literals and removes the
1055 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001056 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +00001057 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001058 return false;
1059 }
Rafael Espindolab7a45052014-11-06 20:01:34 +00001060 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
1061 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
1062 return false;
1063 }
1064
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001065
1066 // Callbacks put into the CRT initializer/terminator sections
1067 // should not be instrumented.
1068 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1069 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1070 if (Section.startswith(".CRT")) {
1071 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1072 return false;
1073 }
1074
Alexander Potapenko04969e82014-03-20 10:48:34 +00001075 // Globals from llvm.metadata aren't emitted, do not instrument them.
1076 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001077 }
1078
1079 return true;
1080}
1081
Alexey Samsonov788381b2012-12-25 12:28:20 +00001082void AddressSanitizerModule::initializeCallbacks(Module &M) {
1083 IRBuilder<> IRB(*C);
1084 // Declare our poisoning and unpoisoning functions.
1085 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001086 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001087 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1088 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001089 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001090 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1091 // Declare functions that register/unregister globals.
1092 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1093 kAsanRegisterGlobalsName, IRB.getVoidTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001094 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001095 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1096 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1097 kAsanUnregisterGlobalsName,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001098 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001099 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1100}
1101
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001102// This function replaces all global variables with new variables that have
1103// trailing redzones. It also creates a function that poisons
1104// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001105bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001106 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001107
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001108 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1109
Alexey Samsonova02e6642014-05-29 18:40:48 +00001110 for (auto &G : M.globals()) {
1111 if (ShouldInstrumentGlobal(&G))
1112 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001113 }
1114
1115 size_t n = GlobalsToChange.size();
1116 if (n == 0) return false;
1117
1118 // A global is described by a structure
1119 // size_t beg;
1120 // size_t size;
1121 // size_t size_with_redzone;
1122 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001123 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001124 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001125 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001126 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001127 StructType *GlobalStructTy =
1128 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001129 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001130 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001131
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001132 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001133
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001134 // We shouldn't merge same module names, as this string serves as unique
1135 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001136 GlobalVariable *ModuleName = createPrivateGlobalForString(
1137 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001138
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001139 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001140 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001141 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001142
1143 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001144 // Create string holding the global name (use global name from metadata
1145 // if it's available, otherwise just write the name of global variable).
1146 GlobalVariable *Name = createPrivateGlobalForString(
1147 M, MD.Name.empty() ? G->getName() : MD.Name,
1148 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001149
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001150 PointerType *PtrTy = cast<PointerType>(G->getType());
1151 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001152 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001153 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001154 // MinRZ <= RZ <= kMaxGlobalRedzone
1155 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001156 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001157 std::min(kMaxGlobalRedzone,
1158 (SizeInBytes / MinRZ / 4) * MinRZ));
1159 uint64_t RightRedzoneSize = RZ;
1160 // Round up to MinRZ
1161 if (SizeInBytes % MinRZ)
1162 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1163 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001164 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1165
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001166 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001167 Constant *NewInitializer = ConstantStruct::get(
1168 NewTy, G->getInitializer(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001169 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001170
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001171 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001172 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1173 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1174 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001175 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001176 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001177 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001178 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001179 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001180
1181 Value *Indices2[2];
1182 Indices2[0] = IRB.getInt32(0);
1183 Indices2[1] = IRB.getInt32(0);
1184
1185 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001186 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001187 NewGlobal->takeName(G);
1188 G->eraseFromParent();
1189
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001190 Constant *SourceLoc;
1191 if (!MD.SourceLoc.empty()) {
1192 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1193 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1194 } else {
1195 SourceLoc = ConstantInt::get(IntptrTy, 0);
1196 }
1197
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001198 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001199 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001200 ConstantInt::get(IntptrTy, SizeInBytes),
1201 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1202 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001203 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001204 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001205
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001206 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001207 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001208
Kostya Serebryany20343352012-10-17 13:40:06 +00001209 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001210 }
1211
1212 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1213 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001214 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001215 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1216
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001217 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001218 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001219 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220 IRB.CreateCall2(AsanRegisterGlobals,
1221 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1222 ConstantInt::get(IntptrTy, n));
1223
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001224 // We also need to unregister globals at the end, e.g. when a shared library
1225 // gets closed.
1226 Function *AsanDtorFunction = Function::Create(
1227 FunctionType::get(Type::getVoidTy(*C), false),
1228 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1229 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1230 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001231 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1232 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1233 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001234 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001235
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001236 DEBUG(dbgs() << M);
1237 return true;
1238}
1239
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001240bool AddressSanitizerModule::runOnModule(Module &M) {
1241 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1242 if (!DLP)
1243 return false;
1244 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001245 C = &(M.getContext());
1246 int LongSize = DL->getPointerSizeInBits();
1247 IntptrTy = Type::getIntNTy(*C, LongSize);
1248 Mapping = getShadowMapping(M, LongSize);
1249 initializeCallbacks(M);
1250
1251 bool Changed = false;
1252
1253 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1254 assert(CtorFunc);
1255 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1256
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001257 if (ClGlobals)
1258 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001259
1260 return Changed;
1261}
1262
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001263void AddressSanitizer::initializeCallbacks(Module &M) {
1264 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001265 // Create __asan_report* callbacks.
1266 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1267 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1268 AccessSizeIndex++) {
1269 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001270 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001271 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001272 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001273 checkInterfaceFunction(
1274 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001275 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001276 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1277 checkInterfaceFunction(
1278 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001279 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001280 }
1281 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001282 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001283 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001284 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001285 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001286
Kostya Serebryany86332c02014-04-21 07:10:43 +00001287 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1288 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001289 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001290 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1291 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001292 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001293
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001294 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1295 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001296 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001297 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1298 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001299 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001300 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1301 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001302 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001303
1304 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001305 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001306
Kostya Serebryany796f6552014-02-27 12:45:36 +00001307 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001308 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001309 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001310 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001311 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1312 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1313 StringRef(""), StringRef(""),
1314 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001315}
1316
1317// virtual
1318bool AddressSanitizer::doInitialization(Module &M) {
1319 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001320 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1321 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001322 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001323 DL = &DLP->getDataLayout();
1324
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001325 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001326
1327 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001328 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001329 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001330
1331 AsanCtorFunction = Function::Create(
1332 FunctionType::get(Type::getVoidTy(*C), false),
1333 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1334 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1335 // call __asan_init in the module ctor.
1336 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1337 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001338 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001339 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1340 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001341
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001342 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001343
Alexey Samsonov1f647502014-05-29 01:10:14 +00001344 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001345 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001346}
1347
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001348bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1349 // For each NSObject descendant having a +load method, this method is invoked
1350 // by the ObjC runtime before any of the static constructors is called.
1351 // Therefore we need to instrument such methods with a call to __asan_init
1352 // at the beginning in order to initialize our runtime before any access to
1353 // the shadow memory.
1354 // We cannot just ignore these methods, because they may call other
1355 // instrumented functions.
1356 if (F.getName().find(" load]") != std::string::npos) {
1357 IRBuilder<> IRB(F.begin()->begin());
1358 IRB.CreateCall(AsanInitFunction);
1359 return true;
1360 }
1361 return false;
1362}
1363
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001364bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001365 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001366 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001367 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001368 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001369
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001370 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001371 maybeInsertAsanInitAtFunctionEntry(F);
1372
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001373 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001374 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001375
1376 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1377 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001378
1379 // We want to instrument every address only once per basic block (unless there
1380 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001381 SmallSet<Value*, 16> TempsToInstrument;
1382 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001383 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001384 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001385 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001386 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001387 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001388 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001389
1390 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001391 for (auto &BB : F) {
1392 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001393 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001394 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001395 for (auto &Inst : BB) {
1396 if (LooksLikeCodeInBug11395(&Inst)) return false;
1397 if (Value *Addr =
1398 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001399 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001400 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001401 continue; // We've seen this temp in the current BB.
1402 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001403 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001404 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1405 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001406 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001407 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001408 // ok, take it.
1409 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001410 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001411 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001412 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001413 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001414 // A call inside BB.
1415 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001416 if (CS.doesNotReturn())
1417 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001418 }
1419 continue;
1420 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001421 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001422 NumInsnsPerBB++;
1423 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1424 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001425 }
1426 }
1427
Craig Topperf40110f2014-04-25 05:29:35 +00001428 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001429 bool LikelyToInstrument =
1430 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1431 if (ClKeepUninstrumented && LikelyToInstrument) {
1432 ValueToValueMapTy VMap;
1433 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1434 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1435 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1436 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1437 }
1438
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001439 bool UseCalls = false;
1440 if (ClInstrumentationWithCallsThreshold >= 0 &&
1441 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1442 UseCalls = true;
1443
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001444 // Instrument.
1445 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001446 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001447 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1448 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001449 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001450 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001451 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001452 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001453 }
1454 NumInstrumented++;
1455 }
1456
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001457 FunctionStackPoisoner FSP(F, *this);
1458 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001459
1460 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1461 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001462 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001463 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001464 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001465 }
1466
Alexey Samsonova02e6642014-05-29 18:40:48 +00001467 for (auto Inst : PointerComparisonsOrSubtracts) {
1468 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001469 NumInstrumented++;
1470 }
1471
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001472 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001473
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001474 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1475
1476 if (ClKeepUninstrumented) {
1477 if (!res) {
1478 // No instrumentation is done, no need for the duplicate.
1479 if (UninstrumentedDuplicate)
1480 UninstrumentedDuplicate->eraseFromParent();
1481 } else {
1482 // The function was instrumented. We must have the duplicate.
1483 assert(UninstrumentedDuplicate);
1484 UninstrumentedDuplicate->setSection("NOASAN");
1485 assert(!F.hasSection());
1486 F.setSection("ASAN");
1487 }
1488 }
1489
1490 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001491}
1492
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001493// Workaround for bug 11395: we don't want to instrument stack in functions
1494// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1495// FIXME: remove once the bug 11395 is fixed.
1496bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1497 if (LongSize != 32) return false;
1498 CallInst *CI = dyn_cast<CallInst>(I);
1499 if (!CI || !CI->isInlineAsm()) return false;
1500 if (CI->getNumArgOperands() <= 5) return false;
1501 // We have inline assembly with quite a few arguments.
1502 return true;
1503}
1504
1505void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1506 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001507 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1508 std::string Suffix = itostr(i);
1509 AsanStackMallocFunc[i] = checkInterfaceFunction(
1510 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001511 IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001512 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1513 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001514 IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001515 }
David Blaikiea92765c2014-11-14 00:41:42 +00001516 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1517 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1518 IntptrTy, IntptrTy, nullptr));
1519 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1520 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1521 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001522}
1523
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001524void
Craig Topper3af97222014-08-27 05:25:00 +00001525FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001526 IRBuilder<> &IRB, Value *ShadowBase,
1527 bool DoPoison) {
1528 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001529 size_t i = 0;
1530 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1531 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1532 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1533 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1534 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1535 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1536 uint64_t Val = 0;
1537 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001538 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001539 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1540 else
1541 Val = (Val << 8) | ShadowBytes[i + j];
1542 }
1543 if (!Val) continue;
1544 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1545 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1546 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1547 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001548 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001549 }
1550}
1551
Kostya Serebryany6805de52013-09-10 13:16:56 +00001552// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1553// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1554static int StackMallocSizeClass(uint64_t LocalStackSize) {
1555 assert(LocalStackSize <= kMaxStackMallocSize);
1556 uint64_t MaxSize = kMinStackMallocSize;
1557 for (int i = 0; ; i++, MaxSize *= 2)
1558 if (LocalStackSize <= MaxSize)
1559 return i;
1560 llvm_unreachable("impossible LocalStackSize");
1561}
1562
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001563// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1564// We can not use MemSet intrinsic because it may end up calling the actual
1565// memset. Size is a multiple of 8.
1566// Currently this generates 8-byte stores on x86_64; it may be better to
1567// generate wider stores.
1568void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1569 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1570 assert(!(Size % 8));
1571 assert(kAsanStackAfterReturnMagic == 0xf5);
1572 for (int i = 0; i < Size; i += 8) {
1573 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1574 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1575 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1576 }
1577}
1578
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001579static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001580 for (const auto &Inst : F.getEntryBlock())
1581 if (!isa<AllocaInst>(Inst))
1582 return Inst.getDebugLoc();
1583 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001584}
1585
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001586void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001587 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1588
1589 if (ClInstrumentAllocas)
1590 // Handle dynamic allocas.
1591 for (auto &AllocaCall : DynamicAllocaVec)
1592 handleDynamicAllocaCall(AllocaCall);
1593
1594 if (AllocaVec.size() == 0) return;
1595
Kostya Serebryany6805de52013-09-10 13:16:56 +00001596 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001597 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001598
1599 Instruction *InsBefore = AllocaVec[0];
1600 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001601 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001602
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001603 SmallVector<ASanStackVariableDescription, 16> SVD;
1604 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001605 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001606 ASanStackVariableDescription D = { AI->getName().data(),
1607 getAllocaSizeInBytes(AI),
1608 AI->getAlignment(), AI, 0};
1609 SVD.push_back(D);
1610 }
1611 // Minimal header size (left redzone) is 4 pointers,
1612 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1613 size_t MinHeaderSize = ASan.LongSize / 2;
1614 ASanStackFrameLayout L;
1615 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1616 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1617 uint64_t LocalStackSize = L.FrameSize;
1618 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001619 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001620
1621 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1622 AllocaInst *MyAlloca =
1623 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001624 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001625 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1626 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1627 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001628 assert(MyAlloca->isStaticAlloca());
1629 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1630 Value *LocalStackBase = OrigStackBase;
1631
1632 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001633 // LocalStackBase = OrigStackBase
1634 // if (__asan_option_detect_stack_use_after_return)
1635 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001636 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1637 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001638 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1639 kAsanOptionDetectUAR, IRB.getInt32Ty());
1640 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1641 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001642 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001643 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1644 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001645 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001646 LocalStackBase = IRBIf.CreateCall2(
1647 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001648 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001649 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1650 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001651 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001652 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1653 Phi->addIncoming(OrigStackBase, CmpBlock);
1654 Phi->addIncoming(LocalStackBase, SetBlock);
1655 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001656 }
1657
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001658 // Insert poison calls for lifetime intrinsics for alloca.
1659 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001660 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001661 assert(APC.InsBefore);
1662 assert(APC.AI);
1663 IRBuilder<> IRB(APC.InsBefore);
1664 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001665 HavePoisonedAllocas |= APC.DoPoison;
1666 }
1667
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001668 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001669 for (const auto &Desc : SVD) {
1670 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001671 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001672 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001673 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001674 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001675 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001676 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001677
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001678 // The left-most redzone has enough space for at least 4 pointers.
1679 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001680 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1681 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1682 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001683 // Write the frame description constant to redzone[1].
1684 Value *BasePlus1 = IRB.CreateIntToPtr(
1685 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1686 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001687 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001688 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1689 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001690 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1691 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001692 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001693 // Write the PC to redzone[2].
1694 Value *BasePlus2 = IRB.CreateIntToPtr(
1695 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1696 2 * ASan.LongSize/8)),
1697 IntptrPtrTy);
1698 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001699
1700 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001701 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001702 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001703
Kostya Serebryany530e2072013-12-23 14:15:08 +00001704 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001705 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001706 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001707 // Mark the current frame as retired.
1708 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1709 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001710 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001711 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001712 // if LocalStackBase != OrigStackBase:
1713 // // In use-after-return mode, poison the whole stack frame.
1714 // if StackMallocIdx <= 4
1715 // // For small sizes inline the whole thing:
1716 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1717 // **SavedFlagPtr(LocalStackBase) = 0
1718 // else
1719 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1720 // else
1721 // <This is not a fake stack; unpoison the redzones>
1722 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1723 TerminatorInst *ThenTerm, *ElseTerm;
1724 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1725
1726 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001727 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001728 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1729 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1730 ClassSize >> Mapping.Scale);
1731 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1732 LocalStackBase,
1733 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1734 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1735 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1736 IRBPoison.CreateStore(
1737 Constant::getNullValue(IRBPoison.getInt8Ty()),
1738 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1739 } else {
1740 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001741 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1742 ConstantInt::get(IntptrTy, LocalStackSize),
1743 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001744 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001745
1746 IRBuilder<> IRBElse(ElseTerm);
1747 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001748 } else if (HavePoisonedAllocas) {
1749 // If we poisoned some allocas in llvm.lifetime analysis,
1750 // unpoison whole stack frame now.
1751 assert(LocalStackBase == OrigStackBase);
1752 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001753 } else {
1754 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001755 }
1756 }
1757
Yury Gribov55441bb2014-11-21 10:29:50 +00001758 if (ClInstrumentAllocas)
1759 // Unpoison dynamic allocas.
1760 for (auto &AllocaCall : DynamicAllocaVec)
1761 unpoisonDynamicAlloca(AllocaCall);
1762
Kostya Serebryany09959942012-10-19 06:20:53 +00001763 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001764 for (auto AI : AllocaVec)
1765 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001766}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001767
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001768void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001769 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001770 // For now just insert the call to ASan runtime.
1771 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1772 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1773 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1774 : AsanUnpoisonStackMemoryFunc,
1775 AddrArg, SizeArg);
1776}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001777
1778// Handling llvm.lifetime intrinsics for a given %alloca:
1779// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1780// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1781// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1782// could be poisoned by previous llvm.lifetime.end instruction, as the
1783// variable may go in and out of scope several times, e.g. in loops).
1784// (3) if we poisoned at least one %alloca in a function,
1785// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001786
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001787AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1788 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1789 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001790 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001791 // See if we've already calculated (or started to calculate) alloca for a
1792 // given value.
1793 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1794 if (I != AllocaForValue.end())
1795 return I->second;
1796 // Store 0 while we're calculating alloca for value V to avoid
1797 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001798 AllocaForValue[V] = nullptr;
1799 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001800 if (CastInst *CI = dyn_cast<CastInst>(V))
1801 Res = findAllocaForValue(CI->getOperand(0));
1802 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1803 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1804 Value *IncValue = PN->getIncomingValue(i);
1805 // Allow self-referencing phi-nodes.
1806 if (IncValue == PN) continue;
1807 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1808 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001809 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1810 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001811 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001812 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001813 }
Craig Topperf40110f2014-04-25 05:29:35 +00001814 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001815 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001816 return Res;
1817}
Yury Gribov55441bb2014-11-21 10:29:50 +00001818
1819// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1820// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1821// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1822// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1823// 8-byte chunk of user memory respectively.
1824// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1825// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1826
1827// Shift = Padding & ~7; // the number of bits we need to shift to access first
1828// chunk in shadow memory, containing nonzero bytes.
1829// Example:
1830// Padding = 21 Padding = 16
1831// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1832// ^ ^
1833// | |
1834// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1835//
1836// Val1 = 0xcbcbcbcb << Shift;
1837// PartialBits = Padding ? Padding & 7 : 0xcb;
1838// Val2 = PartialBits << Shift;
1839// Result = Val1 | Val2;
1840Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1841 IRBuilder<> &IRB) {
1842 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1843 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1844 unsigned Val1Int = kAsanAllocaPartialVal1;
1845 unsigned Val2Int = kAsanAllocaPartialVal2;
1846 if (!ASan.DL->isLittleEndian()) {
1847 Val1Int = sys::getSwappedBytes(Val1Int);
1848 Val2Int = sys::getSwappedBytes(Val2Int);
1849 }
1850 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1851 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1852 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1853 if (ASan.DL->isBigEndian())
1854 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1855 Value *Val2 = IRB.getInt32(Val2Int);
1856 Value *Cond =
1857 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1858 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1859 shiftAllocaMagic(Val2, IRB, Shift));
1860 return IRB.CreateOr(Val1, Val2);
1861}
1862
1863void FunctionStackPoisoner::handleDynamicAllocaCall(
1864 DynamicAllocaCall &AllocaCall) {
1865 AllocaInst *AI = AllocaCall.AI;
1866 IRBuilder<> IRB(AI);
1867
1868 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1869 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1870 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1871
1872 Value *Zero = Constant::getNullValue(IntptrTy);
1873 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1874 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1875 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1876
1877 // Since we need to extend alloca with additional memory to locate
1878 // redzones, and OldSize is number of allocated blocks with
1879 // ElementSize size, get allocated memory size in bytes by
1880 // OldSize * ElementSize.
1881 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1882 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1883 ConstantInt::get(IntptrTy, ElementSize));
1884
1885 // PartialSize = OldSize % 32
1886 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1887
1888 // Misalign = kAllocaRzSize - PartialSize;
1889 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1890
1891 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1892 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1893 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1894
1895 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1896 // Align is added to locate left redzone, PartialPadding for possible
1897 // partial redzone and kAllocaRzSize for right redzone respectively.
1898 Value *AdditionalChunkSize = IRB.CreateAdd(
1899 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1900
1901 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1902
1903 // Insert new alloca with new NewSize and Align params.
1904 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1905 NewAlloca->setAlignment(Align);
1906
1907 // NewAddress = Address + Align
1908 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1909 ConstantInt::get(IntptrTy, Align));
1910
1911 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1912
1913 // LeftRzAddress = NewAddress - kAllocaRzSize
1914 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1915
1916 // Poisoning left redzone.
1917 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1918 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1919 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1920
1921 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1922 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
1923 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
1924
1925 // Poisoning partial redzone.
1926 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
1927 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
1928 IRB.CreateStore(PartialRzMagic,
1929 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
1930
1931 // RightRzAddress
1932 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
1933 Value *RightRzAddress = IRB.CreateAnd(
1934 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
1935
1936 // Poisoning right redzone.
1937 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
1938 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
1939 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
1940
1941 // Replace all uses of AddessReturnedByAlloca with NewAddress.
1942 AI->replaceAllUsesWith(NewAddressPtr);
1943
1944 // We are done. Erase old alloca and store left, partial and right redzones
1945 // shadow addresses for future unpoisoning.
1946 AI->eraseFromParent();
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +00001947 NumInstrumentedDynamicAllocas++;
Yury Gribov55441bb2014-11-21 10:29:50 +00001948}