blob: 14289b114a9c4a132fe1b6965cc7756099bfda7d [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"
Yury Gribov3ae427d2014-12-01 08:47:58 +000030#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000034#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000037#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000040#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/DataTypes.h"
43#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000044#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000045#include "llvm/Support/SwapByteOrder.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000046#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000047#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000049#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000050#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000053#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000054#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000055
56using namespace llvm;
57
Chandler Carruth964daaa2014-04-22 02:55:47 +000058#define DEBUG_TYPE "asan"
59
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060static const uint64_t kDefaultShadowScale = 3;
61static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000062static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000063static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000064static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000065static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000066static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000067static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000068static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000069static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
70static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000071static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000072
Kostya Serebryany6805de52013-09-10 13:16:56 +000073static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000074static const size_t kMaxStackMallocSize = 1 << 16; // 64K
75static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
76static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
77
Craig Topperd3a34f82013-07-16 01:17:10 +000078static const char *const kAsanModuleCtorName = "asan.module_ctor";
79static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000080static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000081static const char *const kAsanReportErrorTemplate = "__asan_report_";
82static const char *const kAsanReportLoadN = "__asan_report_load_n";
83static const char *const kAsanReportStoreN = "__asan_report_store_n";
84static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000085static const char *const kAsanUnregisterGlobalsName =
86 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
88static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000089static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000090static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
91static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000093static const int kMaxAsanStackMallocSizeClass = 10;
94static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
95static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000097static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +000098static const char *const kAsanPoisonStackMemoryName =
99 "__asan_poison_stack_memory";
100static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000101 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000102
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000103static const char *const kAsanOptionDetectUAR =
104 "__asan_option_detect_stack_use_after_return";
105
David Blaikieeacc2872013-09-18 00:11:27 +0000106#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000107static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000108#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000109
Kostya Serebryany874dae62012-07-16 16:15:40 +0000110// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
111static const size_t kNumberOfAccessSizes = 5;
112
Yury Gribov55441bb2014-11-21 10:29:50 +0000113static const unsigned kAllocaRzSize = 32;
114static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
115static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
116static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
117static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
118
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000119// Command-line flags.
120
121// This flag may need to be replaced with -f[no-]asan-reads.
122static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
123 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
124static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
125 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000126static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
127 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
128 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000129static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
130 cl::desc("use instrumentation with slow path for all accesses"),
131 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000132// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000133// in any given BB. Normally, this should be set to unlimited (INT_MAX),
134// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
135// set it to 10000.
136static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
137 cl::init(10000),
138 cl::desc("maximal number of instructions to instrument in any given BB"),
139 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000140// This flag may need to be replaced with -f[no]asan-stack.
141static cl::opt<bool> ClStack("asan-stack",
142 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000143static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000144 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000145// This flag may need to be replaced with -f[no]asan-globals.
146static cl::opt<bool> ClGlobals("asan-globals",
147 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000148static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000149 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000150static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
151 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000152 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000153static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
154 cl::desc("Realign stack to the value of this flag (power of two)"),
155 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000156static cl::opt<int> ClInstrumentationWithCallsThreshold(
157 "asan-instrumentation-with-call-threshold",
158 cl::desc("If the function being instrumented contains more than "
159 "this number of memory accesses, use callbacks instead of "
160 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000161 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000162static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
163 "asan-memory-access-callback-prefix",
164 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
165 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000166static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
167 cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000168
169// These flags allow to change the shadow mapping.
170// The shadow mapping looks like
171// Shadow = (Mem >> scale) + (1 << offset_log)
172static cl::opt<int> ClMappingScale("asan-mapping-scale",
173 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000174
175// Optimization flags. Not user visible, used mostly for testing
176// and benchmarking the tool.
177static cl::opt<bool> ClOpt("asan-opt",
178 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
179static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
180 cl::desc("Instrument the same temp just once"), cl::Hidden,
181 cl::init(true));
182static cl::opt<bool> ClOptGlobals("asan-opt-globals",
183 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
184
Alexey Samsonovdf624522012-11-29 18:14:24 +0000185static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
186 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
187 cl::Hidden, cl::init(false));
188
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000189static cl::opt<bool> ClDynamicAllocaStack(
190 "asan-stack-dynamic-alloca",
191 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
192 cl::init(false));
193
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000194// Debug flags.
195static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
196 cl::init(0));
197static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
198 cl::Hidden, cl::init(0));
199static cl::opt<std::string> ClDebugFunc("asan-debug-func",
200 cl::Hidden, cl::desc("Debug func"));
201static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
202 cl::Hidden, cl::init(-1));
203static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
204 cl::Hidden, cl::init(-1));
205
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000206STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
207STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +0000208STATISTIC(NumInstrumentedDynamicAllocas,
209 "Number of instrumented dynamic allocas");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000210STATISTIC(NumOptimizedAccessesToGlobalArray,
211 "Number of optimized accesses to global arrays");
212STATISTIC(NumOptimizedAccessesToGlobalVar,
213 "Number of optimized accesses to global vars");
214
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000215namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000216/// Frontend-provided metadata for source location.
217struct LocationMetadata {
218 StringRef Filename;
219 int LineNo;
220 int ColumnNo;
221
222 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
223
224 bool empty() const { return Filename.empty(); }
225
226 void parse(MDNode *MDN) {
227 assert(MDN->getNumOperands() == 3);
228 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
229 Filename = MDFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000230 LineNo =
231 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
232 ColumnNo =
233 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000234 }
235};
236
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000237/// Frontend-provided metadata for global variables.
238class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000239 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000240 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000241 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000242 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000243 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000244 LocationMetadata SourceLoc;
245 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000246 bool IsDynInit;
247 bool IsBlacklisted;
248 };
249
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000250 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000251
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000252 void init(Module& M) {
253 assert(!inited_);
254 inited_ = true;
255 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
256 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000257 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000258 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000259 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000260 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000261 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000262 // The optimizer may optimize away a global entirely.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000263 if (!GV)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000264 continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000265 // We can already have an entry for GV if it was merged with another
266 // global.
267 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000268 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
269 E.SourceLoc.parse(Loc);
270 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
271 E.Name = Name->getString();
272 ConstantInt *IsDynInit =
273 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000274 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000275 ConstantInt *IsBlacklisted =
276 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000277 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000278 }
279 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000280
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000281 /// Returns metadata entry for a given global.
282 Entry get(GlobalVariable *G) const {
283 auto Pos = Entries.find(G);
284 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000285 }
286
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000287 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000288 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000289 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000290};
291
Alexey Samsonov1345d352013-01-16 13:23:28 +0000292/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000293/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000294struct ShadowMapping {
295 int Scale;
296 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000297 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000298};
299
Kuba Brecka1001bb52014-12-05 22:19:18 +0000300static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000301 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000302 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000303 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
304 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000305 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
306 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000307 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000308 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
309 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000310 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
311 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000312 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000313 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000314
315 ShadowMapping Mapping;
316
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000317 if (LongSize == 32) {
318 if (IsAndroid)
319 Mapping.Offset = 0;
320 else if (IsMIPS32)
321 Mapping.Offset = kMIPS32_ShadowOffset32;
322 else if (IsFreeBSD)
323 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000324 else if (IsIOS)
325 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000326 else if (IsWindows)
327 Mapping.Offset = kWindowsShadowOffset32;
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;
Renato Golinaf213722015-02-03 11:20:45 +0000339 else if (IsAArch64)
340 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000341 else
342 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000343 }
344
345 Mapping.Scale = kDefaultShadowScale;
346 if (ClMappingScale) {
347 Mapping.Scale = ClMappingScale;
348 }
349
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000350 // OR-ing shadow offset if more efficient (at least on x86) if the offset
351 // is a power of two, but on ppc64 we have to use add since the shadow
352 // offset is not necessary 1/8-th of the address space.
353 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
354
Alexey Samsonov1345d352013-01-16 13:23:28 +0000355 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000356}
357
Alexey Samsonov1345d352013-01-16 13:23:28 +0000358static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000359 // Redzone used for stack and globals is at least 32 bytes.
360 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000361 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000362}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000363
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000364/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000365struct AddressSanitizer : public FunctionPass {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000366 AddressSanitizer() : FunctionPass(ID) {
367 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
368 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000369 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000370 return "AddressSanitizerFunctionPass";
371 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000372 void getAnalysisUsage(AnalysisUsage &AU) const override {
373 AU.addRequired<DominatorTreeWrapperPass>();
374 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000375 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000376 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000377 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
378 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000379 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000380 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
381 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000382 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000383 bool IsWrite, size_t AccessSizeIndex,
384 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000385 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000386 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000387 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000388 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000389 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000390 static char ID; // Pass identification, replacement for typeid
391
Yury Gribov3ae427d2014-12-01 08:47:58 +0000392 DominatorTree &getDominatorTree() const { return *DT; }
393
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000394 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000395 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000396
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000397 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000398 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000399
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000400 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000401 const DataLayout *DL;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000402 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000403 int LongSize;
404 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000405 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000406 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000407 Function *AsanCtorFunction;
408 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000409 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000410 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000411 // This array is indexed by AccessIsWrite and log2(AccessSize).
412 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000413 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000414 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000415 Function *AsanErrorCallbackSized[2],
416 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000417 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000418 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000419 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000420
421 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000422};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000423
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000424class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000425 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000426 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000427 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000428 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000429 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000430 return "AddressSanitizerModule";
431 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000432
Kostya Serebryany20a79972012-11-22 03:18:50 +0000433 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000434 void initializeCallbacks(Module &M);
435
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000436 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000437 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000438 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000439 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000440 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000441 return RedzoneSizeForScale(Mapping.Scale);
442 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000443
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000444 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000445 Type *IntptrTy;
446 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000447 const DataLayout *DL;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000448 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000449 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000450 Function *AsanPoisonGlobals;
451 Function *AsanUnpoisonGlobals;
452 Function *AsanRegisterGlobals;
453 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000454};
455
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000456// Stack poisoning does not play well with exception handling.
457// When an exception is thrown, we essentially bypass the code
458// that unpoisones the stack. This is why the run-time library has
459// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
460// stack in the interceptor. This however does not work inside the
461// actual function which catches the exception. Most likely because the
462// compiler hoists the load of the shadow value somewhere too high.
463// This causes asan to report a non-existing bug on 453.povray.
464// It sounds like an LLVM bug.
465struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
466 Function &F;
467 AddressSanitizer &ASan;
468 DIBuilder DIB;
469 LLVMContext *C;
470 Type *IntptrTy;
471 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000472 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000473
474 SmallVector<AllocaInst*, 16> AllocaVec;
475 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000476 unsigned StackAlignment;
477
Kostya Serebryany6805de52013-09-10 13:16:56 +0000478 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
479 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000480 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
481
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000482 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
483 struct AllocaPoisonCall {
484 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000485 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000486 uint64_t Size;
487 bool DoPoison;
488 };
489 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
490
Yury Gribov55441bb2014-11-21 10:29:50 +0000491 // Stores left and right redzone shadow addresses for dynamic alloca
492 // and pointer to alloca instruction itself.
493 // LeftRzAddr is a shadow address for alloca left redzone.
494 // RightRzAddr is a shadow address for alloca right redzone.
495 struct DynamicAllocaCall {
496 AllocaInst *AI;
497 Value *LeftRzAddr;
498 Value *RightRzAddr;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000499 bool Poison;
Yury Gribov55441bb2014-11-21 10:29:50 +0000500 explicit DynamicAllocaCall(AllocaInst *AI,
501 Value *LeftRzAddr = nullptr,
502 Value *RightRzAddr = nullptr)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000503 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr), Poison(true)
Yury Gribov55441bb2014-11-21 10:29:50 +0000504 {}
505 };
506 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
507
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000508 // Maps Value to an AllocaInst from which the Value is originated.
509 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
510 AllocaForValueMapTy AllocaForValue;
511
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000512 bool HasNonEmptyInlineAsm;
513 std::unique_ptr<CallInst> EmptyInlineAsm;
514
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000515 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000516 : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
517 C(ASan.C), IntptrTy(ASan.IntptrTy),
518 IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000519 StackAlignment(1 << Mapping.Scale), HasNonEmptyInlineAsm(false),
520 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000521
522 bool runOnFunction() {
523 if (!ClStack) return false;
524 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000525 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000526 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000527
Yury Gribov55441bb2014-11-21 10:29:50 +0000528 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000529
530 initializeCallbacks(*F.getParent());
531
532 poisonStack();
533
534 if (ClDebugStack) {
535 DEBUG(dbgs() << F);
536 }
537 return true;
538 }
539
Yury Gribov55441bb2014-11-21 10:29:50 +0000540 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000541 // poisoned red zones around all of them.
542 // Then unpoison everything back before the function returns.
543 void poisonStack();
544
545 // ----------------------- Visitors.
546 /// \brief Collect all Ret instructions.
547 void visitReturnInst(ReturnInst &RI) {
548 RetVec.push_back(&RI);
549 }
550
Yury Gribov55441bb2014-11-21 10:29:50 +0000551 // Unpoison dynamic allocas redzones.
552 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000553 if (!AllocaCall.Poison)
554 return;
Yury Gribov55441bb2014-11-21 10:29:50 +0000555 for (auto Ret : RetVec) {
556 IRBuilder<> IRBRet(Ret);
557 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
558 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
559 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
560 ConstantInt::get(IntptrTy, 4));
561 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
562 Int32PtrTy));
563 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
564 Int32PtrTy));
565 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
566 Int32PtrTy));
567 }
568 }
569
570 // Right shift for BigEndian and left shift for LittleEndian.
571 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
572 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
573 : IRB.CreateLShr(Val, Shift);
574 }
575
576 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
577 // size of requested memory until runtime, we should compute it dynamically.
578 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
579 // otherwise it would contain the value that we will use to poison the
580 // partial redzone for alloca call.
581 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
582
583 // Deploy and poison redzones around dynamic alloca call. To do this, we
584 // should replace this call with another one with changed parameters and
585 // replace all its uses with new address, so
586 // addr = alloca type, old_size, align
587 // is replaced by
588 // new_size = (old_size + additional_size) * sizeof(type)
589 // tmp = alloca i8, new_size, max(align, 32)
590 // addr = tmp + 32 (first 32 bytes are for the left redzone).
591 // Additional_size is added to make new memory allocation contain not only
592 // requested memory, but also left, partial and right redzones.
593 // After that, we should poison redzones:
594 // (1) Left redzone with kAsanAllocaLeftMagic.
595 // (2) Partial redzone with the value, computed in runtime by
596 // computePartialRzMagic function.
597 // (3) Right redzone with kAsanAllocaRightMagic.
598 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
599
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000600 /// \brief Collect Alloca instructions we want (and can) handle.
601 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000602 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000603
604 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000605 if (isDynamicAlloca(AI))
606 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
607 else
608 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000609 }
610
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000611 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
612 /// errors.
613 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000614 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000615 Intrinsic::ID ID = II.getIntrinsicID();
616 if (ID != Intrinsic::lifetime_start &&
617 ID != Intrinsic::lifetime_end)
618 return;
619 // Found lifetime intrinsic, add ASan instrumentation if necessary.
620 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
621 // If size argument is undefined, don't do anything.
622 if (Size->isMinusOne()) return;
623 // Check that size doesn't saturate uint64_t and can
624 // be stored in IntptrTy.
625 const uint64_t SizeValue = Size->getValue().getLimitedValue();
626 if (SizeValue == ~0ULL ||
627 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
628 return;
629 // Find alloca instruction that corresponds to llvm.lifetime argument.
630 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
631 if (!AI) return;
632 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000633 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000634 AllocaPoisonCallVec.push_back(APC);
635 }
636
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000637 void visitCallInst(CallInst &CI) {
638 HasNonEmptyInlineAsm |=
639 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
640 }
641
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000642 // ---------------------- Helpers.
643 void initializeCallbacks(Module &M);
644
Yury Gribov3ae427d2014-12-01 08:47:58 +0000645 bool doesDominateAllExits(const Instruction *I) const {
646 for (auto Ret : RetVec) {
647 if (!ASan.getDominatorTree().dominates(I, Ret))
648 return false;
649 }
650 return true;
651 }
652
Yury Gribov55441bb2014-11-21 10:29:50 +0000653 bool isDynamicAlloca(AllocaInst &AI) const {
654 return AI.isArrayAllocation() || !AI.isStaticAlloca();
655 }
656
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000657 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000658 bool isInterestingAlloca(AllocaInst &AI) const {
Yury Gribov55441bb2014-11-21 10:29:50 +0000659 return (AI.getAllocatedType()->isSized() &&
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000660 // alloca() may be called with 0 size, ignore it.
661 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000662 }
663
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000664 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000665 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000666 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000667 return SizeInBytes;
668 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000669 /// Finds alloca where the value comes from.
670 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000671 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000672 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000673 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000674
675 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
676 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000677 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
678 bool Dynamic);
679 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
680 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000681};
682
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000683} // namespace
684
685char AddressSanitizer::ID = 0;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000686INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan",
687 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
688 false, false)
689INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
690INITIALIZE_PASS_END(AddressSanitizer, "asan",
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000691 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
692 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000693FunctionPass *llvm::createAddressSanitizerFunctionPass() {
694 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000695}
696
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000697char AddressSanitizerModule::ID = 0;
698INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
699 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
700 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000701ModulePass *llvm::createAddressSanitizerModulePass() {
702 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000703}
704
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000705static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000706 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000707 assert(Res < kNumberOfAccessSizes);
708 return Res;
709}
710
Bill Wendling58f8cef2013-08-06 22:52:42 +0000711// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000712static GlobalVariable *createPrivateGlobalForString(
713 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000714 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000715 // We use private linkage for module-local strings. If they can be merged
716 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000717 GlobalVariable *GV =
718 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000719 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
720 if (AllowMerging)
721 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000722 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
723 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000724}
725
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000726/// \brief Create a global describing a source location.
727static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
728 LocationMetadata MD) {
729 Constant *LocData[] = {
730 createPrivateGlobalForString(M, MD.Filename, true),
731 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
732 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
733 };
734 auto LocStruct = ConstantStruct::getAnon(LocData);
735 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
736 GlobalValue::PrivateLinkage, LocStruct,
737 kAsanGenPrefix);
738 GV->setUnnamedAddr(true);
739 return GV;
740}
741
Kostya Serebryany139a9372012-11-20 14:16:08 +0000742static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000743 return G->getName().find(kAsanGenPrefix) == 0 ||
744 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000745}
746
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000747Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
748 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000749 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
750 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000751 return Shadow;
752 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000753 if (Mapping.OrShadowOffset)
754 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
755 else
756 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000757}
758
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000759// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000760void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
761 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000762 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000763 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000764 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
765 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
766 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
767 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
768 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000769 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000770 AsanMemset,
771 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
772 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
773 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000774 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000775 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000776}
777
Kostya Serebryany90241602012-05-30 09:04:06 +0000778// If I is an interesting memory access, return the PointerOperand
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000779// and set IsWrite/Alignment. Otherwise return nullptr.
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000780static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
781 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000782 // Skip memory accesses inserted by another instrumentation.
783 if (I->getMetadata("nosanitize"))
784 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000785 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000786 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000787 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000788 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000789 return LI->getPointerOperand();
790 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000791 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000792 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000793 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000794 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000795 return SI->getPointerOperand();
796 }
797 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000798 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000799 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000800 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000801 return RMW->getPointerOperand();
802 }
803 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000804 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000805 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000806 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000807 return XCHG->getPointerOperand();
808 }
Craig Topperf40110f2014-04-25 05:29:35 +0000809 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000810}
811
Kostya Serebryany796f6552014-02-27 12:45:36 +0000812static bool isPointerOperand(Value *V) {
813 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
814}
815
816// This is a rough heuristic; it may cause both false positives and
817// false negatives. The proper implementation requires cooperation with
818// the frontend.
819static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
820 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
821 if (!Cmp->isRelational())
822 return false;
823 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000824 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000825 return false;
826 } else {
827 return false;
828 }
829 if (!isPointerOperand(I->getOperand(0)) ||
830 !isPointerOperand(I->getOperand(1)))
831 return false;
832 return true;
833}
834
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000835bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
836 // If a global variable does not have dynamic initialization we don't
837 // have to instrument it. However, if a global does not have initializer
838 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000839 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000840}
841
Kostya Serebryany796f6552014-02-27 12:45:36 +0000842void
843AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
844 IRBuilder<> IRB(I);
845 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
846 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
847 for (int i = 0; i < 2; i++) {
848 if (Param[i]->getType()->isPointerTy())
849 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
850 }
851 IRB.CreateCall2(F, Param[0], Param[1]);
852}
853
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000854void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000855 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000856 unsigned Alignment = 0;
857 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000858 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000859 if (ClOpt && ClOptGlobals) {
860 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
861 // If initialization order checking is disabled, a simple access to a
862 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000863 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000864 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000865 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000866 }
867 }
868 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
869 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
870 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
871 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
872 NumOptimizedAccessesToGlobalArray++;
873 return;
874 }
875 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000876 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000877 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000878
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000879 Type *OrigPtrTy = Addr->getType();
880 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
881
882 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000883 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000884
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000885 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000886
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000887 if (IsWrite)
888 NumInstrumentedWrites++;
889 else
890 NumInstrumentedReads++;
891
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000892 unsigned Granularity = 1 << Mapping.Scale;
893 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
894 // if the data is properly aligned.
895 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
896 TypeSize == 128) &&
897 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000898 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000899 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000900 // We can not do it with a single check, so we do 1-byte check for the first
901 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
902 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000903 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000904 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000905 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
906 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000907 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000908 } else {
909 Value *LastByte = IRB.CreateIntToPtr(
910 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
911 OrigPtrTy);
912 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
913 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
914 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000915}
916
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000917// Validate the result of Module::getOrInsertFunction called for an interface
918// function of AddressSanitizer. If the instrumented module defines a function
919// with the same name, their prototypes must match, otherwise
920// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000921static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000922 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
923 FuncOrBitcast->dump();
924 report_fatal_error("trying to redefine an AddressSanitizer "
925 "interface function");
926}
927
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000928Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000929 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000930 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000931 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000932 CallInst *Call = SizeArgument
933 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
934 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
935
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000936 // We don't do Call->setDoesNotReturn() because the BB already has
937 // UnreachableInst at the end.
938 // This EmptyAsm is required to avoid callback merge.
939 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000940 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000941}
942
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000943Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000944 Value *ShadowValue,
945 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000946 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000947 // Addr & (Granularity - 1)
948 Value *LastAccessedByte = IRB.CreateAnd(
949 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
950 // (Addr & (Granularity - 1)) + size - 1
951 if (TypeSize / 8 > 1)
952 LastAccessedByte = IRB.CreateAdd(
953 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
954 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
955 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000956 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000957 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
958 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
959}
960
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000961void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000962 Instruction *InsertBefore, Value *Addr,
963 uint32_t TypeSize, bool IsWrite,
964 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000965 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000966 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000967 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
968
969 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000970 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
971 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000972 return;
973 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000974
975 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000976 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000977 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
978 Value *ShadowPtr = memToShadow(AddrLong, IRB);
979 Value *CmpVal = Constant::getNullValue(ShadowTy);
980 Value *ShadowValue = IRB.CreateLoad(
981 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
982
983 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000984 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000985 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000986
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000987 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000988 // We use branch weights for the slow path check, to indicate that the slow
989 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000990 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000991 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
992 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000993 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000994 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000995 IRB.SetInsertPoint(CheckTerm);
996 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000997 BasicBlock *CrashBlock =
998 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000999 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001000 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1001 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001002 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001003 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001004 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001005
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001006 Instruction *Crash = generateCrashCode(
1007 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001008 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001009}
1010
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001011void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1012 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001013 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001014 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001015
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001016 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001017 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1018 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001019
1020 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001021 for (auto &BB : GlobalInit.getBasicBlockList())
1022 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001023 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001024}
1025
1026void AddressSanitizerModule::createInitializerPoisonCalls(
1027 Module &M, GlobalValue *ModuleName) {
1028 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1029
1030 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1031 for (Use &OP : CA->operands()) {
1032 if (isa<ConstantAggregateZero>(OP))
1033 continue;
1034 ConstantStruct *CS = cast<ConstantStruct>(OP);
1035
1036 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001037 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001038 if (F->getName() == kAsanModuleCtorName) continue;
1039 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1040 // Don't instrument CTORs that will run before asan.module_ctor.
1041 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1042 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001043 }
1044 }
1045}
1046
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001047bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001048 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001049 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001050
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001051 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001052 if (!Ty->isSized()) return false;
1053 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001054 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001055 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001056 // Don't handle ODR linkage types and COMDATs since other modules may be built
1057 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001058 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1059 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1060 G->getLinkage() != GlobalVariable::InternalLinkage)
1061 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001062 if (G->hasComdat())
1063 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001064 // Two problems with thread-locals:
1065 // - The address of the main thread's copy can't be computed at link-time.
1066 // - Need to poison all copies, not just the main thread's one.
1067 if (G->isThreadLocal())
1068 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001069 // For now, just ignore this Global if the alignment is large.
1070 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001071
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001072 if (G->hasSection()) {
1073 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001074
Kuba Brecka1001bb52014-12-05 22:19:18 +00001075 if (TargetTriple.isOSBinFormatMachO()) {
1076 StringRef ParsedSegment, ParsedSection;
1077 unsigned TAA = 0, StubSize = 0;
1078 bool TAAParsed;
1079 std::string ErrorCode =
1080 MCSectionMachO::ParseSectionSpecifier(Section, ParsedSegment,
1081 ParsedSection, TAA, TAAParsed,
1082 StubSize);
1083 if (!ErrorCode.empty()) {
1084 report_fatal_error("Invalid section specifier '" + ParsedSection +
1085 "': " + ErrorCode + ".");
1086 }
1087
1088 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1089 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1090 // them.
1091 if (ParsedSegment == "__OBJC" ||
1092 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1093 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1094 return false;
1095 }
1096 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1097 // Constant CFString instances are compiled in the following way:
1098 // -- the string buffer is emitted into
1099 // __TEXT,__cstring,cstring_literals
1100 // -- the constant NSConstantString structure referencing that buffer
1101 // is placed into __DATA,__cfstring
1102 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1103 // Moreover, it causes the linker to crash on OS X 10.7
1104 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1105 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1106 return false;
1107 }
1108 // The linker merges the contents of cstring_literals and removes the
1109 // trailing zeroes.
1110 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1111 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1112 return false;
1113 }
1114 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001115
1116 // Callbacks put into the CRT initializer/terminator sections
1117 // should not be instrumented.
1118 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1119 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1120 if (Section.startswith(".CRT")) {
1121 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1122 return false;
1123 }
1124
Alexander Potapenko04969e82014-03-20 10:48:34 +00001125 // Globals from llvm.metadata aren't emitted, do not instrument them.
1126 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001127 }
1128
1129 return true;
1130}
1131
Alexey Samsonov788381b2012-12-25 12:28:20 +00001132void AddressSanitizerModule::initializeCallbacks(Module &M) {
1133 IRBuilder<> IRB(*C);
1134 // Declare our poisoning and unpoisoning functions.
1135 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001136 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001137 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1138 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001139 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001140 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1141 // Declare functions that register/unregister globals.
1142 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1143 kAsanRegisterGlobalsName, IRB.getVoidTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001144 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001145 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1146 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1147 kAsanUnregisterGlobalsName,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001148 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001149 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1150}
1151
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001152// This function replaces all global variables with new variables that have
1153// trailing redzones. It also creates a function that poisons
1154// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001155bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001156 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001157
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001158 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1159
Alexey Samsonova02e6642014-05-29 18:40:48 +00001160 for (auto &G : M.globals()) {
1161 if (ShouldInstrumentGlobal(&G))
1162 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001163 }
1164
1165 size_t n = GlobalsToChange.size();
1166 if (n == 0) return false;
1167
1168 // A global is described by a structure
1169 // size_t beg;
1170 // size_t size;
1171 // size_t size_with_redzone;
1172 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001173 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001174 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001175 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001176 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001177 StructType *GlobalStructTy =
1178 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001179 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001180 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001181
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001182 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001183
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001184 // We shouldn't merge same module names, as this string serves as unique
1185 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001186 GlobalVariable *ModuleName = createPrivateGlobalForString(
1187 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001188
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001189 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001190 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001191 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001192
1193 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001194 // Create string holding the global name (use global name from metadata
1195 // if it's available, otherwise just write the name of global variable).
1196 GlobalVariable *Name = createPrivateGlobalForString(
1197 M, MD.Name.empty() ? G->getName() : MD.Name,
1198 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001199
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001200 PointerType *PtrTy = cast<PointerType>(G->getType());
1201 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001202 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001203 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001204 // MinRZ <= RZ <= kMaxGlobalRedzone
1205 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001206 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001207 std::min(kMaxGlobalRedzone,
1208 (SizeInBytes / MinRZ / 4) * MinRZ));
1209 uint64_t RightRedzoneSize = RZ;
1210 // Round up to MinRZ
1211 if (SizeInBytes % MinRZ)
1212 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1213 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001214 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1215
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001216 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001217 Constant *NewInitializer = ConstantStruct::get(
1218 NewTy, G->getInitializer(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001219 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001221 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001222 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1223 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1224 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001225 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001226 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001227 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001228 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001229 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001230
1231 Value *Indices2[2];
1232 Indices2[0] = IRB.getInt32(0);
1233 Indices2[1] = IRB.getInt32(0);
1234
1235 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001236 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001237 NewGlobal->takeName(G);
1238 G->eraseFromParent();
1239
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001240 Constant *SourceLoc;
1241 if (!MD.SourceLoc.empty()) {
1242 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1243 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1244 } else {
1245 SourceLoc = ConstantInt::get(IntptrTy, 0);
1246 }
1247
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001248 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001249 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001250 ConstantInt::get(IntptrTy, SizeInBytes),
1251 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1252 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001253 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001254 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001255
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001256 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001257 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001258
Kostya Serebryany20343352012-10-17 13:40:06 +00001259 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001260 }
1261
1262 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1263 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001264 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001265 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1266
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001267 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001268 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001269 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001270 IRB.CreateCall2(AsanRegisterGlobals,
1271 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1272 ConstantInt::get(IntptrTy, n));
1273
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001274 // We also need to unregister globals at the end, e.g. when a shared library
1275 // gets closed.
1276 Function *AsanDtorFunction = Function::Create(
1277 FunctionType::get(Type::getVoidTy(*C), false),
1278 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1279 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1280 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001281 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1282 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1283 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001284 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001285
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001286 DEBUG(dbgs() << M);
1287 return true;
1288}
1289
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001290bool AddressSanitizerModule::runOnModule(Module &M) {
1291 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1292 if (!DLP)
1293 return false;
1294 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001295 C = &(M.getContext());
1296 int LongSize = DL->getPointerSizeInBits();
1297 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001298 TargetTriple = Triple(M.getTargetTriple());
1299 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001300 initializeCallbacks(M);
1301
1302 bool Changed = false;
1303
1304 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1305 assert(CtorFunc);
1306 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1307
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001308 if (ClGlobals)
1309 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001310
1311 return Changed;
1312}
1313
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001314void AddressSanitizer::initializeCallbacks(Module &M) {
1315 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001316 // Create __asan_report* callbacks.
1317 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1318 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1319 AccessSizeIndex++) {
1320 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001321 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001322 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001323 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001324 checkInterfaceFunction(
1325 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001326 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001327 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1328 checkInterfaceFunction(
1329 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001330 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001331 }
1332 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001333 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001334 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001335 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001336 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001337
Kostya Serebryany86332c02014-04-21 07:10:43 +00001338 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1339 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001340 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001341 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1342 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001343 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001344
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001345 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1346 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001347 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001348 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1349 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001350 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001351 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1352 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001353 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001354
1355 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001356 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001357
Kostya Serebryany796f6552014-02-27 12:45:36 +00001358 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001359 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001360 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001361 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001362 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1363 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1364 StringRef(""), StringRef(""),
1365 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001366}
1367
1368// virtual
1369bool AddressSanitizer::doInitialization(Module &M) {
1370 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001371 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1372 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001373 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001374 DL = &DLP->getDataLayout();
1375
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001376 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001377
1378 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001379 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001380 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001381 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001382
1383 AsanCtorFunction = Function::Create(
1384 FunctionType::get(Type::getVoidTy(*C), false),
1385 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1386 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1387 // call __asan_init in the module ctor.
1388 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1389 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001390 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001391 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1392 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001393
Kuba Brecka1001bb52014-12-05 22:19:18 +00001394 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001395
Alexey Samsonov1f647502014-05-29 01:10:14 +00001396 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001397 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001398}
1399
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001400bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1401 // For each NSObject descendant having a +load method, this method is invoked
1402 // by the ObjC runtime before any of the static constructors is called.
1403 // Therefore we need to instrument such methods with a call to __asan_init
1404 // at the beginning in order to initialize our runtime before any access to
1405 // the shadow memory.
1406 // We cannot just ignore these methods, because they may call other
1407 // instrumented functions.
1408 if (F.getName().find(" load]") != std::string::npos) {
1409 IRBuilder<> IRB(F.begin()->begin());
1410 IRB.CreateCall(AsanInitFunction);
1411 return true;
1412 }
1413 return false;
1414}
1415
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001416bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001417 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001418 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001419 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001420 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001421
Yury Gribov3ae427d2014-12-01 08:47:58 +00001422 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1423
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001424 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001425 maybeInsertAsanInitAtFunctionEntry(F);
1426
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001427 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001428 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001429
1430 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1431 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001432
1433 // We want to instrument every address only once per basic block (unless there
1434 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001435 SmallSet<Value*, 16> TempsToInstrument;
1436 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001437 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001438 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001439 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001440 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001441 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001442 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001443
1444 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001445 for (auto &BB : F) {
1446 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001447 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001448 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001449 for (auto &Inst : BB) {
1450 if (LooksLikeCodeInBug11395(&Inst)) return false;
1451 if (Value *Addr =
1452 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001453 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001454 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001455 continue; // We've seen this temp in the current BB.
1456 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001457 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001458 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1459 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001460 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001461 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001462 // ok, take it.
1463 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001464 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001465 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001466 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001467 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001468 // A call inside BB.
1469 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001470 if (CS.doesNotReturn())
1471 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001472 }
1473 continue;
1474 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001475 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001476 NumInsnsPerBB++;
1477 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1478 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001479 }
1480 }
1481
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001482 bool UseCalls = false;
1483 if (ClInstrumentationWithCallsThreshold >= 0 &&
1484 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1485 UseCalls = true;
1486
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001487 // Instrument.
1488 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001489 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001490 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1491 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001492 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001493 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001494 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001495 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001496 }
1497 NumInstrumented++;
1498 }
1499
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001500 FunctionStackPoisoner FSP(F, *this);
1501 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001502
1503 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1504 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001505 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001506 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001507 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001508 }
1509
Alexey Samsonova02e6642014-05-29 18:40:48 +00001510 for (auto Inst : PointerComparisonsOrSubtracts) {
1511 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001512 NumInstrumented++;
1513 }
1514
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001515 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001516
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001517 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1518
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001519 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001520}
1521
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001522// Workaround for bug 11395: we don't want to instrument stack in functions
1523// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1524// FIXME: remove once the bug 11395 is fixed.
1525bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1526 if (LongSize != 32) return false;
1527 CallInst *CI = dyn_cast<CallInst>(I);
1528 if (!CI || !CI->isInlineAsm()) return false;
1529 if (CI->getNumArgOperands() <= 5) return false;
1530 // We have inline assembly with quite a few arguments.
1531 return true;
1532}
1533
1534void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1535 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001536 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1537 std::string Suffix = itostr(i);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001538 AsanStackMallocFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1539 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy, nullptr));
1540 AsanStackFreeFunc[i] = checkInterfaceFunction(
1541 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1542 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001543 }
David Blaikiea92765c2014-11-14 00:41:42 +00001544 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1545 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1546 IntptrTy, IntptrTy, nullptr));
1547 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1548 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1549 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001550}
1551
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001552void
Craig Topper3af97222014-08-27 05:25:00 +00001553FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001554 IRBuilder<> &IRB, Value *ShadowBase,
1555 bool DoPoison) {
1556 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001557 size_t i = 0;
1558 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1559 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1560 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1561 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1562 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1563 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1564 uint64_t Val = 0;
1565 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001566 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001567 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1568 else
1569 Val = (Val << 8) | ShadowBytes[i + j];
1570 }
1571 if (!Val) continue;
1572 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1573 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1574 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1575 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001576 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001577 }
1578}
1579
Kostya Serebryany6805de52013-09-10 13:16:56 +00001580// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1581// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1582static int StackMallocSizeClass(uint64_t LocalStackSize) {
1583 assert(LocalStackSize <= kMaxStackMallocSize);
1584 uint64_t MaxSize = kMinStackMallocSize;
1585 for (int i = 0; ; i++, MaxSize *= 2)
1586 if (LocalStackSize <= MaxSize)
1587 return i;
1588 llvm_unreachable("impossible LocalStackSize");
1589}
1590
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001591// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1592// We can not use MemSet intrinsic because it may end up calling the actual
1593// memset. Size is a multiple of 8.
1594// Currently this generates 8-byte stores on x86_64; it may be better to
1595// generate wider stores.
1596void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1597 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1598 assert(!(Size % 8));
1599 assert(kAsanStackAfterReturnMagic == 0xf5);
1600 for (int i = 0; i < Size; i += 8) {
1601 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1602 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1603 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1604 }
1605}
1606
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001607static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001608 for (const auto &Inst : F.getEntryBlock())
1609 if (!isa<AllocaInst>(Inst))
1610 return Inst.getDebugLoc();
1611 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001612}
1613
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001614PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1615 Value *ValueIfTrue,
1616 Instruction *ThenTerm,
1617 Value *ValueIfFalse) {
1618 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1619 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1620 PHI->addIncoming(ValueIfFalse, CondBlock);
1621 BasicBlock *ThenBlock = ThenTerm->getParent();
1622 PHI->addIncoming(ValueIfTrue, ThenBlock);
1623 return PHI;
1624}
1625
1626Value *FunctionStackPoisoner::createAllocaForLayout(
1627 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1628 AllocaInst *Alloca;
1629 if (Dynamic) {
1630 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1631 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1632 "MyAlloca");
1633 } else {
1634 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1635 nullptr, "MyAlloca");
1636 assert(Alloca->isStaticAlloca());
1637 }
1638 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1639 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1640 Alloca->setAlignment(FrameAlignment);
1641 return IRB.CreatePointerCast(Alloca, IntptrTy);
1642}
1643
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001644void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001645 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1646
1647 if (ClInstrumentAllocas)
1648 // Handle dynamic allocas.
1649 for (auto &AllocaCall : DynamicAllocaVec)
1650 handleDynamicAllocaCall(AllocaCall);
1651
1652 if (AllocaVec.size() == 0) return;
1653
Kostya Serebryany6805de52013-09-10 13:16:56 +00001654 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001655 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001656
1657 Instruction *InsBefore = AllocaVec[0];
1658 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001659 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001660
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001661 SmallVector<ASanStackVariableDescription, 16> SVD;
1662 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001663 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001664 ASanStackVariableDescription D = { AI->getName().data(),
1665 getAllocaSizeInBytes(AI),
1666 AI->getAlignment(), AI, 0};
1667 SVD.push_back(D);
1668 }
1669 // Minimal header size (left redzone) is 4 pointers,
1670 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1671 size_t MinHeaderSize = ASan.LongSize / 2;
1672 ASanStackFrameLayout L;
1673 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1674 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1675 uint64_t LocalStackSize = L.FrameSize;
1676 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001677 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001678 // Don't do dynamic alloca in presence of inline asm: too often it
1679 // makes assumptions on which registers are available.
1680 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001681
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001682 Value *StaticAlloca =
1683 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1684
1685 Value *FakeStack;
1686 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001687
1688 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001689 // void *FakeStack = __asan_option_detect_stack_use_after_return
1690 // ? __asan_stack_malloc_N(LocalStackSize)
1691 // : nullptr;
1692 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001693 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1694 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001695 Value *UARIsEnabled =
1696 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1697 Constant::getNullValue(IRB.getInt32Ty()));
1698 Instruction *Term =
1699 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001700 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001701 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001702 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1703 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1704 Value *FakeStackValue =
1705 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1706 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001707 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001708 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001709 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1710 ConstantInt::get(IntptrTy, 0));
1711
1712 Value *NoFakeStack =
1713 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1714 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1715 IRBIf.SetInsertPoint(Term);
1716 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1717 Value *AllocaValue =
1718 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1719 IRB.SetInsertPoint(InsBefore);
1720 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1721 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1722 } else {
1723 // void *FakeStack = nullptr;
1724 // void *LocalStackBase = alloca(LocalStackSize);
1725 FakeStack = ConstantInt::get(IntptrTy, 0);
1726 LocalStackBase =
1727 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001728 }
1729
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001730 // Insert poison calls for lifetime intrinsics for alloca.
1731 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001732 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001733 assert(APC.InsBefore);
1734 assert(APC.AI);
1735 IRBuilder<> IRB(APC.InsBefore);
1736 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001737 HavePoisonedAllocas |= APC.DoPoison;
1738 }
1739
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001740 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001741 for (const auto &Desc : SVD) {
1742 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001743 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001744 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001745 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001746 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001747 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001748 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001749
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001750 // The left-most redzone has enough space for at least 4 pointers.
1751 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001752 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1753 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1754 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001755 // Write the frame description constant to redzone[1].
1756 Value *BasePlus1 = IRB.CreateIntToPtr(
1757 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1758 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001759 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001760 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1761 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001762 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1763 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001764 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001765 // Write the PC to redzone[2].
1766 Value *BasePlus2 = IRB.CreateIntToPtr(
1767 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1768 2 * ASan.LongSize/8)),
1769 IntptrPtrTy);
1770 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001771
1772 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001773 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001774 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001775
Kostya Serebryany530e2072013-12-23 14:15:08 +00001776 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001777 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001778 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001779 // Mark the current frame as retired.
1780 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1781 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001782 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001783 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001784 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001785 // // In use-after-return mode, poison the whole stack frame.
1786 // if StackMallocIdx <= 4
1787 // // For small sizes inline the whole thing:
1788 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001789 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001790 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001791 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001792 // else
1793 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001794 Value *Cmp =
1795 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001796 TerminatorInst *ThenTerm, *ElseTerm;
1797 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1798
1799 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001800 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001801 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1802 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1803 ClassSize >> Mapping.Scale);
1804 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001805 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001806 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1807 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1808 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1809 IRBPoison.CreateStore(
1810 Constant::getNullValue(IRBPoison.getInt8Ty()),
1811 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1812 } else {
1813 // For larger frames call __asan_stack_free_*.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001814 IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack,
1815 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001816 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001817
1818 IRBuilder<> IRBElse(ElseTerm);
1819 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001820 } else if (HavePoisonedAllocas) {
1821 // If we poisoned some allocas in llvm.lifetime analysis,
1822 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001823 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001824 } else {
1825 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001826 }
1827 }
1828
Yury Gribov55441bb2014-11-21 10:29:50 +00001829 if (ClInstrumentAllocas)
1830 // Unpoison dynamic allocas.
1831 for (auto &AllocaCall : DynamicAllocaVec)
1832 unpoisonDynamicAlloca(AllocaCall);
1833
Kostya Serebryany09959942012-10-19 06:20:53 +00001834 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001835 for (auto AI : AllocaVec)
1836 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001837}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001838
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001839void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001840 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001841 // For now just insert the call to ASan runtime.
1842 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1843 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1844 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1845 : AsanUnpoisonStackMemoryFunc,
1846 AddrArg, SizeArg);
1847}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001848
1849// Handling llvm.lifetime intrinsics for a given %alloca:
1850// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1851// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1852// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1853// could be poisoned by previous llvm.lifetime.end instruction, as the
1854// variable may go in and out of scope several times, e.g. in loops).
1855// (3) if we poisoned at least one %alloca in a function,
1856// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001857
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001858AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1859 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1860 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001861 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001862 // See if we've already calculated (or started to calculate) alloca for a
1863 // given value.
1864 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1865 if (I != AllocaForValue.end())
1866 return I->second;
1867 // Store 0 while we're calculating alloca for value V to avoid
1868 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001869 AllocaForValue[V] = nullptr;
1870 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001871 if (CastInst *CI = dyn_cast<CastInst>(V))
1872 Res = findAllocaForValue(CI->getOperand(0));
1873 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1875 Value *IncValue = PN->getIncomingValue(i);
1876 // Allow self-referencing phi-nodes.
1877 if (IncValue == PN) continue;
1878 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1879 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001880 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1881 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001882 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001883 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001884 }
Craig Topperf40110f2014-04-25 05:29:35 +00001885 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001886 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001887 return Res;
1888}
Yury Gribov55441bb2014-11-21 10:29:50 +00001889
1890// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1891// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1892// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1893// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1894// 8-byte chunk of user memory respectively.
1895// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1896// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1897
1898// Shift = Padding & ~7; // the number of bits we need to shift to access first
1899// chunk in shadow memory, containing nonzero bytes.
1900// Example:
1901// Padding = 21 Padding = 16
1902// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1903// ^ ^
1904// | |
1905// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1906//
1907// Val1 = 0xcbcbcbcb << Shift;
1908// PartialBits = Padding ? Padding & 7 : 0xcb;
1909// Val2 = PartialBits << Shift;
1910// Result = Val1 | Val2;
1911Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1912 IRBuilder<> &IRB) {
1913 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1914 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1915 unsigned Val1Int = kAsanAllocaPartialVal1;
1916 unsigned Val2Int = kAsanAllocaPartialVal2;
1917 if (!ASan.DL->isLittleEndian()) {
1918 Val1Int = sys::getSwappedBytes(Val1Int);
1919 Val2Int = sys::getSwappedBytes(Val2Int);
1920 }
1921 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1922 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1923 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1924 if (ASan.DL->isBigEndian())
1925 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1926 Value *Val2 = IRB.getInt32(Val2Int);
1927 Value *Cond =
1928 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1929 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1930 shiftAllocaMagic(Val2, IRB, Shift));
1931 return IRB.CreateOr(Val1, Val2);
1932}
1933
1934void FunctionStackPoisoner::handleDynamicAllocaCall(
1935 DynamicAllocaCall &AllocaCall) {
1936 AllocaInst *AI = AllocaCall.AI;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001937 if (!doesDominateAllExits(AI)) {
1938 // We do not yet handle complex allocas
1939 AllocaCall.Poison = false;
1940 return;
1941 }
1942
Yury Gribov55441bb2014-11-21 10:29:50 +00001943 IRBuilder<> IRB(AI);
1944
1945 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1946 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1947 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1948
1949 Value *Zero = Constant::getNullValue(IntptrTy);
1950 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1951 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1952 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1953
1954 // Since we need to extend alloca with additional memory to locate
1955 // redzones, and OldSize is number of allocated blocks with
1956 // ElementSize size, get allocated memory size in bytes by
1957 // OldSize * ElementSize.
1958 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1959 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1960 ConstantInt::get(IntptrTy, ElementSize));
1961
1962 // PartialSize = OldSize % 32
1963 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1964
1965 // Misalign = kAllocaRzSize - PartialSize;
1966 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1967
1968 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1969 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1970 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1971
1972 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1973 // Align is added to locate left redzone, PartialPadding for possible
1974 // partial redzone and kAllocaRzSize for right redzone respectively.
1975 Value *AdditionalChunkSize = IRB.CreateAdd(
1976 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1977
1978 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1979
1980 // Insert new alloca with new NewSize and Align params.
1981 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1982 NewAlloca->setAlignment(Align);
1983
1984 // NewAddress = Address + Align
1985 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1986 ConstantInt::get(IntptrTy, Align));
1987
1988 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1989
1990 // LeftRzAddress = NewAddress - kAllocaRzSize
1991 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1992
1993 // Poisoning left redzone.
1994 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1995 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1996 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1997
1998 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1999 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
2000 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
2001
2002 // Poisoning partial redzone.
2003 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
2004 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
2005 IRB.CreateStore(PartialRzMagic,
2006 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
2007
2008 // RightRzAddress
2009 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
2010 Value *RightRzAddress = IRB.CreateAnd(
2011 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
2012
2013 // Poisoning right redzone.
2014 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
2015 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
2016 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
2017
2018 // Replace all uses of AddessReturnedByAlloca with NewAddress.
2019 AI->replaceAllUsesWith(NewAddressPtr);
2020
2021 // We are done. Erase old alloca and store left, partial and right redzones
2022 // shadow addresses for future unpoisoning.
2023 AI->eraseFromParent();
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +00002024 NumInstrumentedDynamicAllocas++;
Yury Gribov55441bb2014-11-21 10:29:50 +00002025}