blob: 57665cb96766b22993f6a8a4e27970667bf71021 [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;
Kostya Serebryany231bd082014-11-11 23:02:57 +000067static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000068static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
69static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000070
Kostya Serebryany6805de52013-09-10 13:16:56 +000071static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000072static const size_t kMaxStackMallocSize = 1 << 16; // 64K
73static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
74static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
75
Craig Topperd3a34f82013-07-16 01:17:10 +000076static const char *const kAsanModuleCtorName = "asan.module_ctor";
77static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000078static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000079static const char *const kAsanReportErrorTemplate = "__asan_report_";
80static const char *const kAsanReportLoadN = "__asan_report_load_n";
81static const char *const kAsanReportStoreN = "__asan_report_store_n";
82static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000083static const char *const kAsanUnregisterGlobalsName =
84 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000085static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
86static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000087static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000088static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
89static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000091static const int kMaxAsanStackMallocSizeClass = 10;
92static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
93static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000094static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000095static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanPoisonStackMemoryName =
97 "__asan_poison_stack_memory";
98static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000099 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000100
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000101static const char *const kAsanOptionDetectUAR =
102 "__asan_option_detect_stack_use_after_return";
103
David Blaikieeacc2872013-09-18 00:11:27 +0000104#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000105static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000106#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000107
Kostya Serebryany874dae62012-07-16 16:15:40 +0000108// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
109static const size_t kNumberOfAccessSizes = 5;
110
Yury Gribov55441bb2014-11-21 10:29:50 +0000111static const unsigned kAllocaRzSize = 32;
112static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
113static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
114static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
115static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
116
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000117// Command-line flags.
118
119// This flag may need to be replaced with -f[no-]asan-reads.
120static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
121 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
122static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
123 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000124static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
125 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
126 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000127static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
128 cl::desc("use instrumentation with slow path for all accesses"),
129 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000130// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000131// in any given BB. Normally, this should be set to unlimited (INT_MAX),
132// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
133// set it to 10000.
134static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
135 cl::init(10000),
136 cl::desc("maximal number of instructions to instrument in any given BB"),
137 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000138// This flag may need to be replaced with -f[no]asan-stack.
139static cl::opt<bool> ClStack("asan-stack",
140 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000141static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000142 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000143// This flag may need to be replaced with -f[no]asan-globals.
144static cl::opt<bool> ClGlobals("asan-globals",
145 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000146static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000147 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000148static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
149 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000150 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000151static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
152 cl::desc("Realign stack to the value of this flag (power of two)"),
153 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000154static cl::opt<int> ClInstrumentationWithCallsThreshold(
155 "asan-instrumentation-with-call-threshold",
156 cl::desc("If the function being instrumented contains more than "
157 "this number of memory accesses, use callbacks instead of "
158 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000159 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000160static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
161 "asan-memory-access-callback-prefix",
162 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
163 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000164static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
165 cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000166
167// These flags allow to change the shadow mapping.
168// The shadow mapping looks like
169// Shadow = (Mem >> scale) + (1 << offset_log)
170static cl::opt<int> ClMappingScale("asan-mapping-scale",
171 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000172
173// Optimization flags. Not user visible, used mostly for testing
174// and benchmarking the tool.
175static cl::opt<bool> ClOpt("asan-opt",
176 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
177static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
178 cl::desc("Instrument the same temp just once"), cl::Hidden,
179 cl::init(true));
180static cl::opt<bool> ClOptGlobals("asan-opt-globals",
181 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
182
Alexey Samsonovdf624522012-11-29 18:14:24 +0000183static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
184 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
185 cl::Hidden, cl::init(false));
186
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000187static cl::opt<bool> ClDynamicAllocaStack(
188 "asan-stack-dynamic-alloca",
189 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
190 cl::init(false));
191
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000192// Debug flags.
193static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
194 cl::init(0));
195static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
196 cl::Hidden, cl::init(0));
197static cl::opt<std::string> ClDebugFunc("asan-debug-func",
198 cl::Hidden, cl::desc("Debug func"));
199static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
200 cl::Hidden, cl::init(-1));
201static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
202 cl::Hidden, cl::init(-1));
203
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000204STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
205STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +0000206STATISTIC(NumInstrumentedDynamicAllocas,
207 "Number of instrumented dynamic allocas");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000208STATISTIC(NumOptimizedAccessesToGlobalArray,
209 "Number of optimized accesses to global arrays");
210STATISTIC(NumOptimizedAccessesToGlobalVar,
211 "Number of optimized accesses to global vars");
212
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000213namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000214/// Frontend-provided metadata for source location.
215struct LocationMetadata {
216 StringRef Filename;
217 int LineNo;
218 int ColumnNo;
219
220 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
221
222 bool empty() const { return Filename.empty(); }
223
224 void parse(MDNode *MDN) {
225 assert(MDN->getNumOperands() == 3);
226 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
227 Filename = MDFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000228 LineNo =
229 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
230 ColumnNo =
231 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000232 }
233};
234
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000235/// Frontend-provided metadata for global variables.
236class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000237 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000238 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000239 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000240 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000241 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000242 LocationMetadata SourceLoc;
243 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000244 bool IsDynInit;
245 bool IsBlacklisted;
246 };
247
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000248 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000249
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000250 void init(Module& M) {
251 assert(!inited_);
252 inited_ = true;
253 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
254 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000255 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000256 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000257 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000258 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000259 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000260 // The optimizer may optimize away a global entirely.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000261 if (!GV)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000262 continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000263 // We can already have an entry for GV if it was merged with another
264 // global.
265 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000266 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
267 E.SourceLoc.parse(Loc);
268 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
269 E.Name = Name->getString();
270 ConstantInt *IsDynInit =
271 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000272 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000273 ConstantInt *IsBlacklisted =
274 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000275 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000276 }
277 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000278
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000279 /// Returns metadata entry for a given global.
280 Entry get(GlobalVariable *G) const {
281 auto Pos = Entries.find(G);
282 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000283 }
284
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000285 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000286 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000287 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000288};
289
Alexey Samsonov1345d352013-01-16 13:23:28 +0000290/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000291/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000292struct ShadowMapping {
293 int Scale;
294 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000295 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000296};
297
Kuba Brecka1001bb52014-12-05 22:19:18 +0000298static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000299 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000300 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000301 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
302 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000303 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
304 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000305 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000306 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
307 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000308 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
309 TargetTriple.getArch() == llvm::Triple::mips64el;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000310
311 ShadowMapping Mapping;
312
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000313 if (LongSize == 32) {
314 if (IsAndroid)
315 Mapping.Offset = 0;
316 else if (IsMIPS32)
317 Mapping.Offset = kMIPS32_ShadowOffset32;
318 else if (IsFreeBSD)
319 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000320 else if (IsIOS)
321 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000322 else
323 Mapping.Offset = kDefaultShadowOffset32;
324 } else { // LongSize == 64
325 if (IsPPC64)
326 Mapping.Offset = kPPC64_ShadowOffset64;
327 else if (IsFreeBSD)
328 Mapping.Offset = kFreeBSD_ShadowOffset64;
329 else if (IsLinux && IsX86_64)
330 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000331 else if (IsMIPS64)
332 Mapping.Offset = kMIPS64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000333 else
334 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000335 }
336
337 Mapping.Scale = kDefaultShadowScale;
338 if (ClMappingScale) {
339 Mapping.Scale = ClMappingScale;
340 }
341
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000342 // OR-ing shadow offset if more efficient (at least on x86) if the offset
343 // is a power of two, but on ppc64 we have to use add since the shadow
344 // offset is not necessary 1/8-th of the address space.
345 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
346
Alexey Samsonov1345d352013-01-16 13:23:28 +0000347 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000348}
349
Alexey Samsonov1345d352013-01-16 13:23:28 +0000350static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000351 // Redzone used for stack and globals is at least 32 bytes.
352 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000353 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000354}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000355
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000356/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000357struct AddressSanitizer : public FunctionPass {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000358 AddressSanitizer() : FunctionPass(ID) {
359 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
360 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000361 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000362 return "AddressSanitizerFunctionPass";
363 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000364 void getAnalysisUsage(AnalysisUsage &AU) const override {
365 AU.addRequired<DominatorTreeWrapperPass>();
366 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000367 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000368 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000369 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
370 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000371 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000372 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
373 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000374 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000375 bool IsWrite, size_t AccessSizeIndex,
376 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000377 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000378 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000379 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000380 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000381 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000382 static char ID; // Pass identification, replacement for typeid
383
Yury Gribov3ae427d2014-12-01 08:47:58 +0000384 DominatorTree &getDominatorTree() const { return *DT; }
385
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000386 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000387 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000388
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000389 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000390 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000391
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000392 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000393 const DataLayout *DL;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000394 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000395 int LongSize;
396 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000397 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000398 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000399 Function *AsanCtorFunction;
400 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000401 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000402 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000403 // This array is indexed by AccessIsWrite and log2(AccessSize).
404 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000405 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000406 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000407 Function *AsanErrorCallbackSized[2],
408 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000409 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000410 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000411 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000412
413 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000414};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000415
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000416class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000417 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000418 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000419 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000420 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000421 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000422 return "AddressSanitizerModule";
423 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000424
Kostya Serebryany20a79972012-11-22 03:18:50 +0000425 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000426 void initializeCallbacks(Module &M);
427
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000428 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000429 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000430 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000431 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000432 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000433 return RedzoneSizeForScale(Mapping.Scale);
434 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000435
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000436 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000437 Type *IntptrTy;
438 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000439 const DataLayout *DL;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000440 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000441 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000442 Function *AsanPoisonGlobals;
443 Function *AsanUnpoisonGlobals;
444 Function *AsanRegisterGlobals;
445 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000446};
447
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000448// Stack poisoning does not play well with exception handling.
449// When an exception is thrown, we essentially bypass the code
450// that unpoisones the stack. This is why the run-time library has
451// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
452// stack in the interceptor. This however does not work inside the
453// actual function which catches the exception. Most likely because the
454// compiler hoists the load of the shadow value somewhere too high.
455// This causes asan to report a non-existing bug on 453.povray.
456// It sounds like an LLVM bug.
457struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
458 Function &F;
459 AddressSanitizer &ASan;
460 DIBuilder DIB;
461 LLVMContext *C;
462 Type *IntptrTy;
463 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000464 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000465
466 SmallVector<AllocaInst*, 16> AllocaVec;
467 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000468 unsigned StackAlignment;
469
Kostya Serebryany6805de52013-09-10 13:16:56 +0000470 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
471 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000472 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
473
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000474 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
475 struct AllocaPoisonCall {
476 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000477 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000478 uint64_t Size;
479 bool DoPoison;
480 };
481 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
482
Yury Gribov55441bb2014-11-21 10:29:50 +0000483 // Stores left and right redzone shadow addresses for dynamic alloca
484 // and pointer to alloca instruction itself.
485 // LeftRzAddr is a shadow address for alloca left redzone.
486 // RightRzAddr is a shadow address for alloca right redzone.
487 struct DynamicAllocaCall {
488 AllocaInst *AI;
489 Value *LeftRzAddr;
490 Value *RightRzAddr;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000491 bool Poison;
Yury Gribov55441bb2014-11-21 10:29:50 +0000492 explicit DynamicAllocaCall(AllocaInst *AI,
493 Value *LeftRzAddr = nullptr,
494 Value *RightRzAddr = nullptr)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000495 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr), Poison(true)
Yury Gribov55441bb2014-11-21 10:29:50 +0000496 {}
497 };
498 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
499
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000500 // Maps Value to an AllocaInst from which the Value is originated.
501 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
502 AllocaForValueMapTy AllocaForValue;
503
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000504 bool HasNonEmptyInlineAsm;
505 std::unique_ptr<CallInst> EmptyInlineAsm;
506
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000507 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000508 : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
509 C(ASan.C), IntptrTy(ASan.IntptrTy),
510 IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000511 StackAlignment(1 << Mapping.Scale), HasNonEmptyInlineAsm(false),
512 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000513
514 bool runOnFunction() {
515 if (!ClStack) return false;
516 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000517 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000518 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000519
Yury Gribov55441bb2014-11-21 10:29:50 +0000520 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000521
522 initializeCallbacks(*F.getParent());
523
524 poisonStack();
525
526 if (ClDebugStack) {
527 DEBUG(dbgs() << F);
528 }
529 return true;
530 }
531
Yury Gribov55441bb2014-11-21 10:29:50 +0000532 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000533 // poisoned red zones around all of them.
534 // Then unpoison everything back before the function returns.
535 void poisonStack();
536
537 // ----------------------- Visitors.
538 /// \brief Collect all Ret instructions.
539 void visitReturnInst(ReturnInst &RI) {
540 RetVec.push_back(&RI);
541 }
542
Yury Gribov55441bb2014-11-21 10:29:50 +0000543 // Unpoison dynamic allocas redzones.
544 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000545 if (!AllocaCall.Poison)
546 return;
Yury Gribov55441bb2014-11-21 10:29:50 +0000547 for (auto Ret : RetVec) {
548 IRBuilder<> IRBRet(Ret);
549 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
550 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
551 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
552 ConstantInt::get(IntptrTy, 4));
553 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
554 Int32PtrTy));
555 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
556 Int32PtrTy));
557 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
558 Int32PtrTy));
559 }
560 }
561
562 // Right shift for BigEndian and left shift for LittleEndian.
563 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
564 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
565 : IRB.CreateLShr(Val, Shift);
566 }
567
568 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
569 // size of requested memory until runtime, we should compute it dynamically.
570 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
571 // otherwise it would contain the value that we will use to poison the
572 // partial redzone for alloca call.
573 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
574
575 // Deploy and poison redzones around dynamic alloca call. To do this, we
576 // should replace this call with another one with changed parameters and
577 // replace all its uses with new address, so
578 // addr = alloca type, old_size, align
579 // is replaced by
580 // new_size = (old_size + additional_size) * sizeof(type)
581 // tmp = alloca i8, new_size, max(align, 32)
582 // addr = tmp + 32 (first 32 bytes are for the left redzone).
583 // Additional_size is added to make new memory allocation contain not only
584 // requested memory, but also left, partial and right redzones.
585 // After that, we should poison redzones:
586 // (1) Left redzone with kAsanAllocaLeftMagic.
587 // (2) Partial redzone with the value, computed in runtime by
588 // computePartialRzMagic function.
589 // (3) Right redzone with kAsanAllocaRightMagic.
590 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
591
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000592 /// \brief Collect Alloca instructions we want (and can) handle.
593 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000594 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000595
596 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000597 if (isDynamicAlloca(AI))
598 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
599 else
600 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000601 }
602
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000603 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
604 /// errors.
605 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000606 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000607 Intrinsic::ID ID = II.getIntrinsicID();
608 if (ID != Intrinsic::lifetime_start &&
609 ID != Intrinsic::lifetime_end)
610 return;
611 // Found lifetime intrinsic, add ASan instrumentation if necessary.
612 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
613 // If size argument is undefined, don't do anything.
614 if (Size->isMinusOne()) return;
615 // Check that size doesn't saturate uint64_t and can
616 // be stored in IntptrTy.
617 const uint64_t SizeValue = Size->getValue().getLimitedValue();
618 if (SizeValue == ~0ULL ||
619 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
620 return;
621 // Find alloca instruction that corresponds to llvm.lifetime argument.
622 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
623 if (!AI) return;
624 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000625 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000626 AllocaPoisonCallVec.push_back(APC);
627 }
628
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000629 void visitCallInst(CallInst &CI) {
630 HasNonEmptyInlineAsm |=
631 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
632 }
633
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000634 // ---------------------- Helpers.
635 void initializeCallbacks(Module &M);
636
Yury Gribov3ae427d2014-12-01 08:47:58 +0000637 bool doesDominateAllExits(const Instruction *I) const {
638 for (auto Ret : RetVec) {
639 if (!ASan.getDominatorTree().dominates(I, Ret))
640 return false;
641 }
642 return true;
643 }
644
Yury Gribov55441bb2014-11-21 10:29:50 +0000645 bool isDynamicAlloca(AllocaInst &AI) const {
646 return AI.isArrayAllocation() || !AI.isStaticAlloca();
647 }
648
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000649 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000650 bool isInterestingAlloca(AllocaInst &AI) const {
Yury Gribov55441bb2014-11-21 10:29:50 +0000651 return (AI.getAllocatedType()->isSized() &&
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000652 // alloca() may be called with 0 size, ignore it.
653 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000654 }
655
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000656 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000657 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000658 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000659 return SizeInBytes;
660 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000661 /// Finds alloca where the value comes from.
662 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000663 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000664 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000665 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000666
667 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
668 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000669 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
670 bool Dynamic);
671 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
672 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000673};
674
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000675} // namespace
676
677char AddressSanitizer::ID = 0;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000678INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan",
679 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
680 false, false)
681INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
682INITIALIZE_PASS_END(AddressSanitizer, "asan",
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000683 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
684 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000685FunctionPass *llvm::createAddressSanitizerFunctionPass() {
686 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000687}
688
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000689char AddressSanitizerModule::ID = 0;
690INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
691 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
692 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000693ModulePass *llvm::createAddressSanitizerModulePass() {
694 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000695}
696
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000697static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000698 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000699 assert(Res < kNumberOfAccessSizes);
700 return Res;
701}
702
Bill Wendling58f8cef2013-08-06 22:52:42 +0000703// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000704static GlobalVariable *createPrivateGlobalForString(
705 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000706 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000707 // We use private linkage for module-local strings. If they can be merged
708 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000709 GlobalVariable *GV =
710 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000711 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
712 if (AllowMerging)
713 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000714 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
715 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000716}
717
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000718/// \brief Create a global describing a source location.
719static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
720 LocationMetadata MD) {
721 Constant *LocData[] = {
722 createPrivateGlobalForString(M, MD.Filename, true),
723 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
724 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
725 };
726 auto LocStruct = ConstantStruct::getAnon(LocData);
727 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
728 GlobalValue::PrivateLinkage, LocStruct,
729 kAsanGenPrefix);
730 GV->setUnnamedAddr(true);
731 return GV;
732}
733
Kostya Serebryany139a9372012-11-20 14:16:08 +0000734static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000735 return G->getName().find(kAsanGenPrefix) == 0 ||
736 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000737}
738
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000739Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
740 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000741 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
742 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000743 return Shadow;
744 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000745 if (Mapping.OrShadowOffset)
746 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
747 else
748 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000749}
750
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000751// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000752void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
753 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000754 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000755 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000756 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
757 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
758 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
759 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
760 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000761 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000762 AsanMemset,
763 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
764 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
765 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000766 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000767 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000768}
769
Kostya Serebryany90241602012-05-30 09:04:06 +0000770// If I is an interesting memory access, return the PointerOperand
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000771// and set IsWrite/Alignment. Otherwise return nullptr.
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000772static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
773 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000774 // Skip memory accesses inserted by another instrumentation.
775 if (I->getMetadata("nosanitize"))
776 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000777 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000778 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000779 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000780 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000781 return LI->getPointerOperand();
782 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000783 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000784 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000785 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000786 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000787 return SI->getPointerOperand();
788 }
789 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000790 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000791 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000792 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000793 return RMW->getPointerOperand();
794 }
795 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000796 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000797 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000798 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000799 return XCHG->getPointerOperand();
800 }
Craig Topperf40110f2014-04-25 05:29:35 +0000801 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000802}
803
Kostya Serebryany796f6552014-02-27 12:45:36 +0000804static bool isPointerOperand(Value *V) {
805 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
806}
807
808// This is a rough heuristic; it may cause both false positives and
809// false negatives. The proper implementation requires cooperation with
810// the frontend.
811static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
812 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
813 if (!Cmp->isRelational())
814 return false;
815 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000816 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000817 return false;
818 } else {
819 return false;
820 }
821 if (!isPointerOperand(I->getOperand(0)) ||
822 !isPointerOperand(I->getOperand(1)))
823 return false;
824 return true;
825}
826
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000827bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
828 // If a global variable does not have dynamic initialization we don't
829 // have to instrument it. However, if a global does not have initializer
830 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000831 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000832}
833
Kostya Serebryany796f6552014-02-27 12:45:36 +0000834void
835AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
836 IRBuilder<> IRB(I);
837 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
838 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
839 for (int i = 0; i < 2; i++) {
840 if (Param[i]->getType()->isPointerTy())
841 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
842 }
843 IRB.CreateCall2(F, Param[0], Param[1]);
844}
845
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000846void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000847 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000848 unsigned Alignment = 0;
849 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000850 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000851 if (ClOpt && ClOptGlobals) {
852 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
853 // If initialization order checking is disabled, a simple access to a
854 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000855 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000856 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000857 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000858 }
859 }
860 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
861 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
862 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
863 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
864 NumOptimizedAccessesToGlobalArray++;
865 return;
866 }
867 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000868 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000869 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000870
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000871 Type *OrigPtrTy = Addr->getType();
872 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
873
874 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000875 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000876
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000877 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000878
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000879 if (IsWrite)
880 NumInstrumentedWrites++;
881 else
882 NumInstrumentedReads++;
883
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000884 unsigned Granularity = 1 << Mapping.Scale;
885 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
886 // if the data is properly aligned.
887 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
888 TypeSize == 128) &&
889 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000890 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000891 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000892 // We can not do it with a single check, so we do 1-byte check for the first
893 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
894 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000895 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000896 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000897 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
898 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000899 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000900 } else {
901 Value *LastByte = IRB.CreateIntToPtr(
902 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
903 OrigPtrTy);
904 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
905 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
906 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000907}
908
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000909// Validate the result of Module::getOrInsertFunction called for an interface
910// function of AddressSanitizer. If the instrumented module defines a function
911// with the same name, their prototypes must match, otherwise
912// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000913static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000914 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
915 FuncOrBitcast->dump();
916 report_fatal_error("trying to redefine an AddressSanitizer "
917 "interface function");
918}
919
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000920Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000921 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000922 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000923 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000924 CallInst *Call = SizeArgument
925 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
926 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
927
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000928 // We don't do Call->setDoesNotReturn() because the BB already has
929 // UnreachableInst at the end.
930 // This EmptyAsm is required to avoid callback merge.
931 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000932 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000933}
934
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000935Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000936 Value *ShadowValue,
937 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000938 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000939 // Addr & (Granularity - 1)
940 Value *LastAccessedByte = IRB.CreateAnd(
941 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
942 // (Addr & (Granularity - 1)) + size - 1
943 if (TypeSize / 8 > 1)
944 LastAccessedByte = IRB.CreateAdd(
945 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
946 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
947 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000948 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000949 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
950 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
951}
952
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000953void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000954 Instruction *InsertBefore, Value *Addr,
955 uint32_t TypeSize, bool IsWrite,
956 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000957 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000958 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000959 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
960
961 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000962 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
963 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000964 return;
965 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000966
967 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000968 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000969 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
970 Value *ShadowPtr = memToShadow(AddrLong, IRB);
971 Value *CmpVal = Constant::getNullValue(ShadowTy);
972 Value *ShadowValue = IRB.CreateLoad(
973 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
974
975 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000976 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000977 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000978
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000979 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000980 // We use branch weights for the slow path check, to indicate that the slow
981 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000982 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000983 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
984 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000985 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000986 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000987 IRB.SetInsertPoint(CheckTerm);
988 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000989 BasicBlock *CrashBlock =
990 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000991 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000992 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
993 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000994 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000995 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000996 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000997
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000998 Instruction *Crash = generateCrashCode(
999 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001000 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001001}
1002
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001003void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1004 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001005 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001006 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001007
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001008 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001009 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1010 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001011
1012 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001013 for (auto &BB : GlobalInit.getBasicBlockList())
1014 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001015 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001016}
1017
1018void AddressSanitizerModule::createInitializerPoisonCalls(
1019 Module &M, GlobalValue *ModuleName) {
1020 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1021
1022 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1023 for (Use &OP : CA->operands()) {
1024 if (isa<ConstantAggregateZero>(OP))
1025 continue;
1026 ConstantStruct *CS = cast<ConstantStruct>(OP);
1027
1028 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001029 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001030 if (F->getName() == kAsanModuleCtorName) continue;
1031 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1032 // Don't instrument CTORs that will run before asan.module_ctor.
1033 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1034 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001035 }
1036 }
1037}
1038
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001039bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001040 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001041 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001042
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001043 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001044 if (!Ty->isSized()) return false;
1045 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001046 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001047 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001048 // Don't handle ODR linkage types and COMDATs since other modules may be built
1049 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001050 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1051 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1052 G->getLinkage() != GlobalVariable::InternalLinkage)
1053 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001054 if (G->hasComdat())
1055 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001056 // Two problems with thread-locals:
1057 // - The address of the main thread's copy can't be computed at link-time.
1058 // - Need to poison all copies, not just the main thread's one.
1059 if (G->isThreadLocal())
1060 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001061 // For now, just ignore this Global if the alignment is large.
1062 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001063
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001064 if (G->hasSection()) {
1065 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001066
Kuba Brecka1001bb52014-12-05 22:19:18 +00001067 if (TargetTriple.isOSBinFormatMachO()) {
1068 StringRef ParsedSegment, ParsedSection;
1069 unsigned TAA = 0, StubSize = 0;
1070 bool TAAParsed;
1071 std::string ErrorCode =
1072 MCSectionMachO::ParseSectionSpecifier(Section, ParsedSegment,
1073 ParsedSection, TAA, TAAParsed,
1074 StubSize);
1075 if (!ErrorCode.empty()) {
1076 report_fatal_error("Invalid section specifier '" + ParsedSection +
1077 "': " + ErrorCode + ".");
1078 }
1079
1080 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1081 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1082 // them.
1083 if (ParsedSegment == "__OBJC" ||
1084 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1085 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1086 return false;
1087 }
1088 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1089 // Constant CFString instances are compiled in the following way:
1090 // -- the string buffer is emitted into
1091 // __TEXT,__cstring,cstring_literals
1092 // -- the constant NSConstantString structure referencing that buffer
1093 // is placed into __DATA,__cfstring
1094 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1095 // Moreover, it causes the linker to crash on OS X 10.7
1096 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1097 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1098 return false;
1099 }
1100 // The linker merges the contents of cstring_literals and removes the
1101 // trailing zeroes.
1102 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1103 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1104 return false;
1105 }
1106 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001107
1108 // Callbacks put into the CRT initializer/terminator sections
1109 // should not be instrumented.
1110 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1111 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1112 if (Section.startswith(".CRT")) {
1113 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1114 return false;
1115 }
1116
Alexander Potapenko04969e82014-03-20 10:48:34 +00001117 // Globals from llvm.metadata aren't emitted, do not instrument them.
1118 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001119 }
1120
1121 return true;
1122}
1123
Alexey Samsonov788381b2012-12-25 12:28:20 +00001124void AddressSanitizerModule::initializeCallbacks(Module &M) {
1125 IRBuilder<> IRB(*C);
1126 // Declare our poisoning and unpoisoning functions.
1127 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001128 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001129 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1130 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001131 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001132 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1133 // Declare functions that register/unregister globals.
1134 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1135 kAsanRegisterGlobalsName, IRB.getVoidTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001136 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001137 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1138 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1139 kAsanUnregisterGlobalsName,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001140 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001141 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1142}
1143
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001144// This function replaces all global variables with new variables that have
1145// trailing redzones. It also creates a function that poisons
1146// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001147bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001148 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001149
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001150 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1151
Alexey Samsonova02e6642014-05-29 18:40:48 +00001152 for (auto &G : M.globals()) {
1153 if (ShouldInstrumentGlobal(&G))
1154 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001155 }
1156
1157 size_t n = GlobalsToChange.size();
1158 if (n == 0) return false;
1159
1160 // A global is described by a structure
1161 // size_t beg;
1162 // size_t size;
1163 // size_t size_with_redzone;
1164 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001165 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001166 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001167 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001168 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001169 StructType *GlobalStructTy =
1170 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001171 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001172 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001173
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001174 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001175
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001176 // We shouldn't merge same module names, as this string serves as unique
1177 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001178 GlobalVariable *ModuleName = createPrivateGlobalForString(
1179 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001180
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001181 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001182 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001183 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001184
1185 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001186 // Create string holding the global name (use global name from metadata
1187 // if it's available, otherwise just write the name of global variable).
1188 GlobalVariable *Name = createPrivateGlobalForString(
1189 M, MD.Name.empty() ? G->getName() : MD.Name,
1190 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001191
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001192 PointerType *PtrTy = cast<PointerType>(G->getType());
1193 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001194 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001195 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001196 // MinRZ <= RZ <= kMaxGlobalRedzone
1197 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001198 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001199 std::min(kMaxGlobalRedzone,
1200 (SizeInBytes / MinRZ / 4) * MinRZ));
1201 uint64_t RightRedzoneSize = RZ;
1202 // Round up to MinRZ
1203 if (SizeInBytes % MinRZ)
1204 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1205 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001206 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1207
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001208 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001209 Constant *NewInitializer = ConstantStruct::get(
1210 NewTy, G->getInitializer(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001211 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001212
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001213 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001214 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1215 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1216 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001217 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001218 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001219 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001221 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001222
1223 Value *Indices2[2];
1224 Indices2[0] = IRB.getInt32(0);
1225 Indices2[1] = IRB.getInt32(0);
1226
1227 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001228 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001229 NewGlobal->takeName(G);
1230 G->eraseFromParent();
1231
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001232 Constant *SourceLoc;
1233 if (!MD.SourceLoc.empty()) {
1234 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1235 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1236 } else {
1237 SourceLoc = ConstantInt::get(IntptrTy, 0);
1238 }
1239
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001240 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001241 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001242 ConstantInt::get(IntptrTy, SizeInBytes),
1243 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1244 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001245 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001246 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001247
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001248 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001249 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001250
Kostya Serebryany20343352012-10-17 13:40:06 +00001251 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001252 }
1253
1254 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1255 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001256 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001257 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1258
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001259 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001260 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001261 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001262 IRB.CreateCall2(AsanRegisterGlobals,
1263 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1264 ConstantInt::get(IntptrTy, n));
1265
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001266 // We also need to unregister globals at the end, e.g. when a shared library
1267 // gets closed.
1268 Function *AsanDtorFunction = Function::Create(
1269 FunctionType::get(Type::getVoidTy(*C), false),
1270 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1271 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1272 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001273 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1274 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1275 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001276 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001277
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001278 DEBUG(dbgs() << M);
1279 return true;
1280}
1281
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001282bool AddressSanitizerModule::runOnModule(Module &M) {
1283 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1284 if (!DLP)
1285 return false;
1286 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001287 C = &(M.getContext());
1288 int LongSize = DL->getPointerSizeInBits();
1289 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001290 TargetTriple = Triple(M.getTargetTriple());
1291 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001292 initializeCallbacks(M);
1293
1294 bool Changed = false;
1295
1296 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1297 assert(CtorFunc);
1298 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1299
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001300 if (ClGlobals)
1301 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001302
1303 return Changed;
1304}
1305
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001306void AddressSanitizer::initializeCallbacks(Module &M) {
1307 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001308 // Create __asan_report* callbacks.
1309 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1310 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1311 AccessSizeIndex++) {
1312 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001313 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001314 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001315 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001316 checkInterfaceFunction(
1317 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001318 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001319 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1320 checkInterfaceFunction(
1321 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001322 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001323 }
1324 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001325 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001326 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001327 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001328 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001329
Kostya Serebryany86332c02014-04-21 07:10:43 +00001330 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1331 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001332 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001333 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1334 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001335 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001336
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001337 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1338 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001339 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001340 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1341 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001342 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001343 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1344 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001345 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001346
1347 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001348 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001349
Kostya Serebryany796f6552014-02-27 12:45:36 +00001350 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001351 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001352 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001353 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001354 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1355 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1356 StringRef(""), StringRef(""),
1357 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001358}
1359
1360// virtual
1361bool AddressSanitizer::doInitialization(Module &M) {
1362 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001363 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1364 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001365 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001366 DL = &DLP->getDataLayout();
1367
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001368 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001369
1370 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001371 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001372 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001373 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001374
1375 AsanCtorFunction = Function::Create(
1376 FunctionType::get(Type::getVoidTy(*C), false),
1377 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1378 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1379 // call __asan_init in the module ctor.
1380 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1381 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001382 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001383 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1384 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001385
Kuba Brecka1001bb52014-12-05 22:19:18 +00001386 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001387
Alexey Samsonov1f647502014-05-29 01:10:14 +00001388 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001389 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001390}
1391
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001392bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1393 // For each NSObject descendant having a +load method, this method is invoked
1394 // by the ObjC runtime before any of the static constructors is called.
1395 // Therefore we need to instrument such methods with a call to __asan_init
1396 // at the beginning in order to initialize our runtime before any access to
1397 // the shadow memory.
1398 // We cannot just ignore these methods, because they may call other
1399 // instrumented functions.
1400 if (F.getName().find(" load]") != std::string::npos) {
1401 IRBuilder<> IRB(F.begin()->begin());
1402 IRB.CreateCall(AsanInitFunction);
1403 return true;
1404 }
1405 return false;
1406}
1407
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001408bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001409 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001410 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001411 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001412 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001413
Yury Gribov3ae427d2014-12-01 08:47:58 +00001414 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1415
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001416 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001417 maybeInsertAsanInitAtFunctionEntry(F);
1418
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001419 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001420 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001421
1422 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1423 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001424
1425 // We want to instrument every address only once per basic block (unless there
1426 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001427 SmallSet<Value*, 16> TempsToInstrument;
1428 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001429 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001430 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001431 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001432 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001433 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001434 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001435
1436 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001437 for (auto &BB : F) {
1438 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001439 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001440 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001441 for (auto &Inst : BB) {
1442 if (LooksLikeCodeInBug11395(&Inst)) return false;
1443 if (Value *Addr =
1444 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001445 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001446 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001447 continue; // We've seen this temp in the current BB.
1448 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001449 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001450 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1451 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001452 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001453 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001454 // ok, take it.
1455 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001456 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001457 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001458 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001459 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001460 // A call inside BB.
1461 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001462 if (CS.doesNotReturn())
1463 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001464 }
1465 continue;
1466 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001467 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001468 NumInsnsPerBB++;
1469 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1470 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001471 }
1472 }
1473
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001474 bool UseCalls = false;
1475 if (ClInstrumentationWithCallsThreshold >= 0 &&
1476 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1477 UseCalls = true;
1478
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001479 // Instrument.
1480 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001481 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001482 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1483 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001484 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001485 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001486 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001487 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001488 }
1489 NumInstrumented++;
1490 }
1491
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001492 FunctionStackPoisoner FSP(F, *this);
1493 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001494
1495 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1496 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001497 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001498 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001499 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001500 }
1501
Alexey Samsonova02e6642014-05-29 18:40:48 +00001502 for (auto Inst : PointerComparisonsOrSubtracts) {
1503 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001504 NumInstrumented++;
1505 }
1506
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001507 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001508
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001509 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1510
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001511 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001512}
1513
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001514// Workaround for bug 11395: we don't want to instrument stack in functions
1515// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1516// FIXME: remove once the bug 11395 is fixed.
1517bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1518 if (LongSize != 32) return false;
1519 CallInst *CI = dyn_cast<CallInst>(I);
1520 if (!CI || !CI->isInlineAsm()) return false;
1521 if (CI->getNumArgOperands() <= 5) return false;
1522 // We have inline assembly with quite a few arguments.
1523 return true;
1524}
1525
1526void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1527 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001528 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1529 std::string Suffix = itostr(i);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001530 AsanStackMallocFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1531 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy, nullptr));
1532 AsanStackFreeFunc[i] = checkInterfaceFunction(
1533 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1534 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001535 }
David Blaikiea92765c2014-11-14 00:41:42 +00001536 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1537 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1538 IntptrTy, IntptrTy, nullptr));
1539 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1540 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1541 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001542}
1543
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001544void
Craig Topper3af97222014-08-27 05:25:00 +00001545FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001546 IRBuilder<> &IRB, Value *ShadowBase,
1547 bool DoPoison) {
1548 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001549 size_t i = 0;
1550 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1551 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1552 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1553 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1554 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1555 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1556 uint64_t Val = 0;
1557 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001558 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001559 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1560 else
1561 Val = (Val << 8) | ShadowBytes[i + j];
1562 }
1563 if (!Val) continue;
1564 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1565 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1566 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1567 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001568 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001569 }
1570}
1571
Kostya Serebryany6805de52013-09-10 13:16:56 +00001572// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1573// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1574static int StackMallocSizeClass(uint64_t LocalStackSize) {
1575 assert(LocalStackSize <= kMaxStackMallocSize);
1576 uint64_t MaxSize = kMinStackMallocSize;
1577 for (int i = 0; ; i++, MaxSize *= 2)
1578 if (LocalStackSize <= MaxSize)
1579 return i;
1580 llvm_unreachable("impossible LocalStackSize");
1581}
1582
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001583// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1584// We can not use MemSet intrinsic because it may end up calling the actual
1585// memset. Size is a multiple of 8.
1586// Currently this generates 8-byte stores on x86_64; it may be better to
1587// generate wider stores.
1588void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1589 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1590 assert(!(Size % 8));
1591 assert(kAsanStackAfterReturnMagic == 0xf5);
1592 for (int i = 0; i < Size; i += 8) {
1593 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1594 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1595 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1596 }
1597}
1598
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001599static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001600 for (const auto &Inst : F.getEntryBlock())
1601 if (!isa<AllocaInst>(Inst))
1602 return Inst.getDebugLoc();
1603 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001604}
1605
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001606PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1607 Value *ValueIfTrue,
1608 Instruction *ThenTerm,
1609 Value *ValueIfFalse) {
1610 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1611 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1612 PHI->addIncoming(ValueIfFalse, CondBlock);
1613 BasicBlock *ThenBlock = ThenTerm->getParent();
1614 PHI->addIncoming(ValueIfTrue, ThenBlock);
1615 return PHI;
1616}
1617
1618Value *FunctionStackPoisoner::createAllocaForLayout(
1619 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1620 AllocaInst *Alloca;
1621 if (Dynamic) {
1622 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1623 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1624 "MyAlloca");
1625 } else {
1626 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1627 nullptr, "MyAlloca");
1628 assert(Alloca->isStaticAlloca());
1629 }
1630 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1631 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1632 Alloca->setAlignment(FrameAlignment);
1633 return IRB.CreatePointerCast(Alloca, IntptrTy);
1634}
1635
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001636void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001637 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1638
1639 if (ClInstrumentAllocas)
1640 // Handle dynamic allocas.
1641 for (auto &AllocaCall : DynamicAllocaVec)
1642 handleDynamicAllocaCall(AllocaCall);
1643
1644 if (AllocaVec.size() == 0) return;
1645
Kostya Serebryany6805de52013-09-10 13:16:56 +00001646 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001647 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001648
1649 Instruction *InsBefore = AllocaVec[0];
1650 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001651 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001652
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001653 SmallVector<ASanStackVariableDescription, 16> SVD;
1654 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001655 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001656 ASanStackVariableDescription D = { AI->getName().data(),
1657 getAllocaSizeInBytes(AI),
1658 AI->getAlignment(), AI, 0};
1659 SVD.push_back(D);
1660 }
1661 // Minimal header size (left redzone) is 4 pointers,
1662 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1663 size_t MinHeaderSize = ASan.LongSize / 2;
1664 ASanStackFrameLayout L;
1665 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1666 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1667 uint64_t LocalStackSize = L.FrameSize;
1668 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001669 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001670 // Don't do dynamic alloca in presence of inline asm: too often it
1671 // makes assumptions on which registers are available.
1672 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001673
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001674 Value *StaticAlloca =
1675 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1676
1677 Value *FakeStack;
1678 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001679
1680 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001681 // void *FakeStack = __asan_option_detect_stack_use_after_return
1682 // ? __asan_stack_malloc_N(LocalStackSize)
1683 // : nullptr;
1684 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001685 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1686 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001687 Value *UARIsEnabled =
1688 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1689 Constant::getNullValue(IRB.getInt32Ty()));
1690 Instruction *Term =
1691 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001692 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001693 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001694 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1695 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1696 Value *FakeStackValue =
1697 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1698 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001699 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001700 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001701 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1702 ConstantInt::get(IntptrTy, 0));
1703
1704 Value *NoFakeStack =
1705 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1706 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1707 IRBIf.SetInsertPoint(Term);
1708 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1709 Value *AllocaValue =
1710 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1711 IRB.SetInsertPoint(InsBefore);
1712 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1713 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1714 } else {
1715 // void *FakeStack = nullptr;
1716 // void *LocalStackBase = alloca(LocalStackSize);
1717 FakeStack = ConstantInt::get(IntptrTy, 0);
1718 LocalStackBase =
1719 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001720 }
1721
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001722 // Insert poison calls for lifetime intrinsics for alloca.
1723 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001724 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001725 assert(APC.InsBefore);
1726 assert(APC.AI);
1727 IRBuilder<> IRB(APC.InsBefore);
1728 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001729 HavePoisonedAllocas |= APC.DoPoison;
1730 }
1731
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001732 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001733 for (const auto &Desc : SVD) {
1734 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001735 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001736 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001737 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001738 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001739 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001740 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001741
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001742 // The left-most redzone has enough space for at least 4 pointers.
1743 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001744 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1745 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1746 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001747 // Write the frame description constant to redzone[1].
1748 Value *BasePlus1 = IRB.CreateIntToPtr(
1749 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1750 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001751 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001752 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1753 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001754 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1755 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001756 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001757 // Write the PC to redzone[2].
1758 Value *BasePlus2 = IRB.CreateIntToPtr(
1759 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1760 2 * ASan.LongSize/8)),
1761 IntptrPtrTy);
1762 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001763
1764 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001765 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001766 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001767
Kostya Serebryany530e2072013-12-23 14:15:08 +00001768 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001769 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001770 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001771 // Mark the current frame as retired.
1772 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1773 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001774 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001775 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001776 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001777 // // In use-after-return mode, poison the whole stack frame.
1778 // if StackMallocIdx <= 4
1779 // // For small sizes inline the whole thing:
1780 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001781 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001782 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001783 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001784 // else
1785 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001786 Value *Cmp =
1787 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001788 TerminatorInst *ThenTerm, *ElseTerm;
1789 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1790
1791 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001792 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001793 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1794 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1795 ClassSize >> Mapping.Scale);
1796 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001797 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001798 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1799 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1800 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1801 IRBPoison.CreateStore(
1802 Constant::getNullValue(IRBPoison.getInt8Ty()),
1803 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1804 } else {
1805 // For larger frames call __asan_stack_free_*.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001806 IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack,
1807 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001808 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001809
1810 IRBuilder<> IRBElse(ElseTerm);
1811 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001812 } else if (HavePoisonedAllocas) {
1813 // If we poisoned some allocas in llvm.lifetime analysis,
1814 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001815 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001816 } else {
1817 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001818 }
1819 }
1820
Yury Gribov55441bb2014-11-21 10:29:50 +00001821 if (ClInstrumentAllocas)
1822 // Unpoison dynamic allocas.
1823 for (auto &AllocaCall : DynamicAllocaVec)
1824 unpoisonDynamicAlloca(AllocaCall);
1825
Kostya Serebryany09959942012-10-19 06:20:53 +00001826 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001827 for (auto AI : AllocaVec)
1828 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001829}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001830
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001831void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001832 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001833 // For now just insert the call to ASan runtime.
1834 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1835 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1836 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1837 : AsanUnpoisonStackMemoryFunc,
1838 AddrArg, SizeArg);
1839}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001840
1841// Handling llvm.lifetime intrinsics for a given %alloca:
1842// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1843// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1844// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1845// could be poisoned by previous llvm.lifetime.end instruction, as the
1846// variable may go in and out of scope several times, e.g. in loops).
1847// (3) if we poisoned at least one %alloca in a function,
1848// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001849
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001850AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1851 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1852 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001853 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001854 // See if we've already calculated (or started to calculate) alloca for a
1855 // given value.
1856 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1857 if (I != AllocaForValue.end())
1858 return I->second;
1859 // Store 0 while we're calculating alloca for value V to avoid
1860 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001861 AllocaForValue[V] = nullptr;
1862 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001863 if (CastInst *CI = dyn_cast<CastInst>(V))
1864 Res = findAllocaForValue(CI->getOperand(0));
1865 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1866 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1867 Value *IncValue = PN->getIncomingValue(i);
1868 // Allow self-referencing phi-nodes.
1869 if (IncValue == PN) continue;
1870 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1871 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001872 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1873 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001874 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001875 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001876 }
Craig Topperf40110f2014-04-25 05:29:35 +00001877 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001878 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001879 return Res;
1880}
Yury Gribov55441bb2014-11-21 10:29:50 +00001881
1882// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1883// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1884// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1885// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1886// 8-byte chunk of user memory respectively.
1887// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1888// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1889
1890// Shift = Padding & ~7; // the number of bits we need to shift to access first
1891// chunk in shadow memory, containing nonzero bytes.
1892// Example:
1893// Padding = 21 Padding = 16
1894// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1895// ^ ^
1896// | |
1897// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1898//
1899// Val1 = 0xcbcbcbcb << Shift;
1900// PartialBits = Padding ? Padding & 7 : 0xcb;
1901// Val2 = PartialBits << Shift;
1902// Result = Val1 | Val2;
1903Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1904 IRBuilder<> &IRB) {
1905 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1906 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1907 unsigned Val1Int = kAsanAllocaPartialVal1;
1908 unsigned Val2Int = kAsanAllocaPartialVal2;
1909 if (!ASan.DL->isLittleEndian()) {
1910 Val1Int = sys::getSwappedBytes(Val1Int);
1911 Val2Int = sys::getSwappedBytes(Val2Int);
1912 }
1913 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1914 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1915 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1916 if (ASan.DL->isBigEndian())
1917 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1918 Value *Val2 = IRB.getInt32(Val2Int);
1919 Value *Cond =
1920 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1921 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1922 shiftAllocaMagic(Val2, IRB, Shift));
1923 return IRB.CreateOr(Val1, Val2);
1924}
1925
1926void FunctionStackPoisoner::handleDynamicAllocaCall(
1927 DynamicAllocaCall &AllocaCall) {
1928 AllocaInst *AI = AllocaCall.AI;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001929 if (!doesDominateAllExits(AI)) {
1930 // We do not yet handle complex allocas
1931 AllocaCall.Poison = false;
1932 return;
1933 }
1934
Yury Gribov55441bb2014-11-21 10:29:50 +00001935 IRBuilder<> IRB(AI);
1936
1937 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1938 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1939 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1940
1941 Value *Zero = Constant::getNullValue(IntptrTy);
1942 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1943 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1944 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1945
1946 // Since we need to extend alloca with additional memory to locate
1947 // redzones, and OldSize is number of allocated blocks with
1948 // ElementSize size, get allocated memory size in bytes by
1949 // OldSize * ElementSize.
1950 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1951 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1952 ConstantInt::get(IntptrTy, ElementSize));
1953
1954 // PartialSize = OldSize % 32
1955 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1956
1957 // Misalign = kAllocaRzSize - PartialSize;
1958 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1959
1960 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1961 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1962 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1963
1964 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1965 // Align is added to locate left redzone, PartialPadding for possible
1966 // partial redzone and kAllocaRzSize for right redzone respectively.
1967 Value *AdditionalChunkSize = IRB.CreateAdd(
1968 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1969
1970 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1971
1972 // Insert new alloca with new NewSize and Align params.
1973 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1974 NewAlloca->setAlignment(Align);
1975
1976 // NewAddress = Address + Align
1977 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1978 ConstantInt::get(IntptrTy, Align));
1979
1980 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1981
1982 // LeftRzAddress = NewAddress - kAllocaRzSize
1983 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1984
1985 // Poisoning left redzone.
1986 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1987 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1988 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1989
1990 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1991 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
1992 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
1993
1994 // Poisoning partial redzone.
1995 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
1996 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
1997 IRB.CreateStore(PartialRzMagic,
1998 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
1999
2000 // RightRzAddress
2001 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
2002 Value *RightRzAddress = IRB.CreateAnd(
2003 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
2004
2005 // Poisoning right redzone.
2006 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
2007 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
2008 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
2009
2010 // Replace all uses of AddessReturnedByAlloca with NewAddress.
2011 AI->replaceAllUsesWith(NewAddressPtr);
2012
2013 // We are done. Erase old alloca and store left, partial and right redzones
2014 // shadow addresses for future unpoisoning.
2015 AI->eraseFromParent();
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +00002016 NumInstrumentedDynamicAllocas++;
Yury Gribov55441bb2014-11-21 10:29:50 +00002017}