blob: 38f587fc186ac19a3d26ecba281682744ba433be [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000019#include "llvm/ADT/DenseSet.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000020#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000024#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000025#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000028#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000033#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000036#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
38#include "llvm/IR/Type.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000042#include "llvm/Support/Endian.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000043#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000044#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000046#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000047#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000048#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000049#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000051#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052
53using namespace llvm;
54
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "asan"
56
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057static const uint64_t kDefaultShadowScale = 3;
58static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000059static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000061static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000062static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000063static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kostya Serebryany231bd082014-11-11 23:02:57 +000064static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000065static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
66static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067
Kostya Serebryany6805de52013-09-10 13:16:56 +000068static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000069static const size_t kMaxStackMallocSize = 1 << 16; // 64K
70static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
71static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
72
Craig Topperd3a34f82013-07-16 01:17:10 +000073static const char *const kAsanModuleCtorName = "asan.module_ctor";
74static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000075static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000076static const char *const kAsanReportErrorTemplate = "__asan_report_";
77static const char *const kAsanReportLoadN = "__asan_report_load_n";
78static const char *const kAsanReportStoreN = "__asan_report_store_n";
79static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000080static const char *const kAsanUnregisterGlobalsName =
81 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000082static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
83static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000084static const char *const kAsanInitName = "__asan_init_v4";
Kostya Serebryany796f6552014-02-27 12:45:36 +000085static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
86static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000088static const int kMaxAsanStackMallocSizeClass = 10;
89static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
90static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000092static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +000093static const char *const kAsanPoisonStackMemoryName =
94 "__asan_poison_stack_memory";
95static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000096 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000097
Kostya Serebryanyf3223822013-09-18 14:07:14 +000098static const char *const kAsanOptionDetectUAR =
99 "__asan_option_detect_stack_use_after_return";
100
David Blaikieeacc2872013-09-18 00:11:27 +0000101#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000102static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000103#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000104
Kostya Serebryany874dae62012-07-16 16:15:40 +0000105// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
106static const size_t kNumberOfAccessSizes = 5;
107
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000108// Command-line flags.
109
110// This flag may need to be replaced with -f[no-]asan-reads.
111static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
112 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
113static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
114 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000115static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
116 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
117 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000118static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
119 cl::desc("use instrumentation with slow path for all accesses"),
120 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000121// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000122// in any given BB. Normally, this should be set to unlimited (INT_MAX),
123// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
124// set it to 10000.
125static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
126 cl::init(10000),
127 cl::desc("maximal number of instructions to instrument in any given BB"),
128 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000129// This flag may need to be replaced with -f[no]asan-stack.
130static cl::opt<bool> ClStack("asan-stack",
131 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000132static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000133 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000134// This flag may need to be replaced with -f[no]asan-globals.
135static cl::opt<bool> ClGlobals("asan-globals",
136 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000137static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000138 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000139static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
140 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000141 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000142static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
143 cl::desc("Realign stack to the value of this flag (power of two)"),
144 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000145static cl::opt<int> ClInstrumentationWithCallsThreshold(
146 "asan-instrumentation-with-call-threshold",
147 cl::desc("If the function being instrumented contains more than "
148 "this number of memory accesses, use callbacks instead of "
149 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000150 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000151static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
152 "asan-memory-access-callback-prefix",
153 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
154 cl::init("__asan_"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000155
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000156// This is an experimental feature that will allow to choose between
157// instrumented and non-instrumented code at link-time.
158// If this option is on, just before instrumenting a function we create its
159// clone; if the function is not changed by asan the clone is deleted.
160// If we end up with a clone, we put the instrumented function into a section
161// called "ASAN" and the uninstrumented function into a section called "NOASAN".
162//
163// This is still a prototype, we need to figure out a way to keep two copies of
164// a function so that the linker can easily choose one of them.
165static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
166 cl::desc("Keep uninstrumented copies of functions"),
167 cl::Hidden, cl::init(false));
168
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000169// These flags allow to change the shadow mapping.
170// The shadow mapping looks like
171// Shadow = (Mem >> scale) + (1 << offset_log)
172static cl::opt<int> ClMappingScale("asan-mapping-scale",
173 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000174
175// Optimization flags. Not user visible, used mostly for testing
176// and benchmarking the tool.
177static cl::opt<bool> ClOpt("asan-opt",
178 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
179static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
180 cl::desc("Instrument the same temp just once"), cl::Hidden,
181 cl::init(true));
182static cl::opt<bool> ClOptGlobals("asan-opt-globals",
183 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
184
Alexey Samsonovdf624522012-11-29 18:14:24 +0000185static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
186 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
187 cl::Hidden, cl::init(false));
188
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000189// Debug flags.
190static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
191 cl::init(0));
192static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
193 cl::Hidden, cl::init(0));
194static cl::opt<std::string> ClDebugFunc("asan-debug-func",
195 cl::Hidden, cl::desc("Debug func"));
196static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
197 cl::Hidden, cl::init(-1));
198static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
199 cl::Hidden, cl::init(-1));
200
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000201STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
202STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
203STATISTIC(NumOptimizedAccessesToGlobalArray,
204 "Number of optimized accesses to global arrays");
205STATISTIC(NumOptimizedAccessesToGlobalVar,
206 "Number of optimized accesses to global vars");
207
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000208namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000209/// Frontend-provided metadata for source location.
210struct LocationMetadata {
211 StringRef Filename;
212 int LineNo;
213 int ColumnNo;
214
215 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
216
217 bool empty() const { return Filename.empty(); }
218
219 void parse(MDNode *MDN) {
220 assert(MDN->getNumOperands() == 3);
221 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
222 Filename = MDFilename->getString();
223 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
224 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
225 }
226};
227
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000228/// Frontend-provided metadata for global variables.
229class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000230 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000231 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000232 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000233 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000234 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000235 LocationMetadata SourceLoc;
236 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000237 bool IsDynInit;
238 bool IsBlacklisted;
239 };
240
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000241 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000242
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000243 void init(Module& M) {
244 assert(!inited_);
245 inited_ = true;
246 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
247 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000248 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000249 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000250 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000251 assert(MDN->getNumOperands() == 5);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000252 Value *V = MDN->getOperand(0);
253 // The optimizer may optimize away a global entirely.
254 if (!V)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000255 continue;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000256 GlobalVariable *GV = cast<GlobalVariable>(V);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000257 // We can already have an entry for GV if it was merged with another
258 // global.
259 Entry &E = Entries[GV];
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000260 if (Value *Loc = MDN->getOperand(1))
261 E.SourceLoc.parse(cast<MDNode>(Loc));
Alexey Samsonov15c96692014-07-12 00:42:52 +0000262 if (Value *Name = MDN->getOperand(2)) {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000263 MDString *MDName = cast<MDString>(Name);
264 E.Name = MDName->getString();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000265 }
266 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000267 E.IsDynInit |= IsDynInit->isOne();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000268 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000269 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000270 }
271 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000272
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000273 /// Returns metadata entry for a given global.
274 Entry get(GlobalVariable *G) const {
275 auto Pos = Entries.find(G);
276 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000277 }
278
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000279 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000280 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000281 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000282};
283
Alexey Samsonov1345d352013-01-16 13:23:28 +0000284/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000285/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000286struct ShadowMapping {
287 int Scale;
288 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000289 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000290};
291
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000292static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000293 llvm::Triple TargetTriple(M.getTargetTriple());
294 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000295 bool IsIOS = TargetTriple.isiOS();
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000296 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000297 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000298 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
299 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000300 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000301 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
302 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000303 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
304 TargetTriple.getArch() == llvm::Triple::mips64el;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000305
306 ShadowMapping Mapping;
307
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000308 if (LongSize == 32) {
309 if (IsAndroid)
310 Mapping.Offset = 0;
311 else if (IsMIPS32)
312 Mapping.Offset = kMIPS32_ShadowOffset32;
313 else if (IsFreeBSD)
314 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000315 else if (IsIOS)
316 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000317 else
318 Mapping.Offset = kDefaultShadowOffset32;
319 } else { // LongSize == 64
320 if (IsPPC64)
321 Mapping.Offset = kPPC64_ShadowOffset64;
322 else if (IsFreeBSD)
323 Mapping.Offset = kFreeBSD_ShadowOffset64;
324 else if (IsLinux && IsX86_64)
325 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000326 else if (IsMIPS64)
327 Mapping.Offset = kMIPS64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000328 else
329 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000330 }
331
332 Mapping.Scale = kDefaultShadowScale;
333 if (ClMappingScale) {
334 Mapping.Scale = ClMappingScale;
335 }
336
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000337 // OR-ing shadow offset if more efficient (at least on x86) if the offset
338 // is a power of two, but on ppc64 we have to use add since the shadow
339 // offset is not necessary 1/8-th of the address space.
340 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
341
Alexey Samsonov1345d352013-01-16 13:23:28 +0000342 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000343}
344
Alexey Samsonov1345d352013-01-16 13:23:28 +0000345static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000346 // Redzone used for stack and globals is at least 32 bytes.
347 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000348 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000349}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000350
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000351/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000352struct AddressSanitizer : public FunctionPass {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000353 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000354 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000355 return "AddressSanitizerFunctionPass";
356 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000357 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000358 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000359 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
360 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000361 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000362 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
363 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000364 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000365 bool IsWrite, size_t AccessSizeIndex,
366 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000367 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000368 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000369 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000370 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000371 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000372 static char ID; // Pass identification, replacement for typeid
373
374 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000375 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000376
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000377 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000378 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000379
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000380 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000381 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000382 int LongSize;
383 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000384 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000385 Function *AsanCtorFunction;
386 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000387 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000388 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000389 // This array is indexed by AccessIsWrite and log2(AccessSize).
390 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000391 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000392 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000393 Function *AsanErrorCallbackSized[2],
394 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000395 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000396 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000397 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000398
399 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000400};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000401
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000402class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000403 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000404 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000405 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000406 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000407 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000408 return "AddressSanitizerModule";
409 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000410
Kostya Serebryany20a79972012-11-22 03:18:50 +0000411 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000412 void initializeCallbacks(Module &M);
413
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000414 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000415 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000416 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000417 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000418 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000419 return RedzoneSizeForScale(Mapping.Scale);
420 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000421
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000422 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000423 Type *IntptrTy;
424 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000425 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000426 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000427 Function *AsanPoisonGlobals;
428 Function *AsanUnpoisonGlobals;
429 Function *AsanRegisterGlobals;
430 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000431};
432
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000433// Stack poisoning does not play well with exception handling.
434// When an exception is thrown, we essentially bypass the code
435// that unpoisones the stack. This is why the run-time library has
436// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
437// stack in the interceptor. This however does not work inside the
438// actual function which catches the exception. Most likely because the
439// compiler hoists the load of the shadow value somewhere too high.
440// This causes asan to report a non-existing bug on 453.povray.
441// It sounds like an LLVM bug.
442struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
443 Function &F;
444 AddressSanitizer &ASan;
445 DIBuilder DIB;
446 LLVMContext *C;
447 Type *IntptrTy;
448 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000449 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000450
451 SmallVector<AllocaInst*, 16> AllocaVec;
452 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000453 unsigned StackAlignment;
454
Kostya Serebryany6805de52013-09-10 13:16:56 +0000455 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
456 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000457 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
458
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000459 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
460 struct AllocaPoisonCall {
461 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000462 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000463 uint64_t Size;
464 bool DoPoison;
465 };
466 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
467
468 // Maps Value to an AllocaInst from which the Value is originated.
469 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
470 AllocaForValueMapTy AllocaForValue;
471
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000472 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
473 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
474 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000475 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000476 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000477
478 bool runOnFunction() {
479 if (!ClStack) return false;
480 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000481 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000482 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000483
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000484 if (AllocaVec.empty()) return false;
485
486 initializeCallbacks(*F.getParent());
487
488 poisonStack();
489
490 if (ClDebugStack) {
491 DEBUG(dbgs() << F);
492 }
493 return true;
494 }
495
496 // Finds all static Alloca instructions and puts
497 // poisoned red zones around all of them.
498 // Then unpoison everything back before the function returns.
499 void poisonStack();
500
501 // ----------------------- Visitors.
502 /// \brief Collect all Ret instructions.
503 void visitReturnInst(ReturnInst &RI) {
504 RetVec.push_back(&RI);
505 }
506
507 /// \brief Collect Alloca instructions we want (and can) handle.
508 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000509 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000510
511 StackAlignment = std::max(StackAlignment, AI.getAlignment());
512 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000513 }
514
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000515 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
516 /// errors.
517 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000518 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000519 Intrinsic::ID ID = II.getIntrinsicID();
520 if (ID != Intrinsic::lifetime_start &&
521 ID != Intrinsic::lifetime_end)
522 return;
523 // Found lifetime intrinsic, add ASan instrumentation if necessary.
524 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
525 // If size argument is undefined, don't do anything.
526 if (Size->isMinusOne()) return;
527 // Check that size doesn't saturate uint64_t and can
528 // be stored in IntptrTy.
529 const uint64_t SizeValue = Size->getValue().getLimitedValue();
530 if (SizeValue == ~0ULL ||
531 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
532 return;
533 // Find alloca instruction that corresponds to llvm.lifetime argument.
534 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
535 if (!AI) return;
536 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000537 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000538 AllocaPoisonCallVec.push_back(APC);
539 }
540
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000541 // ---------------------- Helpers.
542 void initializeCallbacks(Module &M);
543
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000544 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000545 bool isInterestingAlloca(AllocaInst &AI) const {
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000546 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
547 AI.getAllocatedType()->isSized() &&
548 // alloca() may be called with 0 size, ignore it.
549 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000550 }
551
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000552 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000553 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000554 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000555 return SizeInBytes;
556 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000557 /// Finds alloca where the value comes from.
558 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000559 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000560 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000561 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000562
563 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
564 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000565};
566
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000567} // namespace
568
569char AddressSanitizer::ID = 0;
570INITIALIZE_PASS(AddressSanitizer, "asan",
571 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
572 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000573FunctionPass *llvm::createAddressSanitizerFunctionPass() {
574 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000575}
576
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000577char AddressSanitizerModule::ID = 0;
578INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
579 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
580 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000581ModulePass *llvm::createAddressSanitizerModulePass() {
582 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000583}
584
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000585static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000586 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000587 assert(Res < kNumberOfAccessSizes);
588 return Res;
589}
590
Bill Wendling58f8cef2013-08-06 22:52:42 +0000591// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000592static GlobalVariable *createPrivateGlobalForString(
593 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000594 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000595 // We use private linkage for module-local strings. If they can be merged
596 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000597 GlobalVariable *GV =
598 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000599 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
600 if (AllowMerging)
601 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000602 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
603 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000604}
605
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000606/// \brief Create a global describing a source location.
607static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
608 LocationMetadata MD) {
609 Constant *LocData[] = {
610 createPrivateGlobalForString(M, MD.Filename, true),
611 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
612 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
613 };
614 auto LocStruct = ConstantStruct::getAnon(LocData);
615 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
616 GlobalValue::PrivateLinkage, LocStruct,
617 kAsanGenPrefix);
618 GV->setUnnamedAddr(true);
619 return GV;
620}
621
Kostya Serebryany139a9372012-11-20 14:16:08 +0000622static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000623 return G->getName().find(kAsanGenPrefix) == 0 ||
624 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000625}
626
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000627Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
628 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000629 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
630 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000631 return Shadow;
632 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000633 if (Mapping.OrShadowOffset)
634 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
635 else
636 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000637}
638
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000639// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000640void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
641 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000642 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000643 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000644 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
645 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
646 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
647 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
648 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000649 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000650 AsanMemset,
651 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
652 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
653 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000654 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000655 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000656}
657
Kostya Serebryany90241602012-05-30 09:04:06 +0000658// If I is an interesting memory access, return the PointerOperand
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000659// and set IsWrite/Alignment. Otherwise return nullptr.
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000660static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
661 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000662 // Skip memory accesses inserted by another instrumentation.
663 if (I->getMetadata("nosanitize"))
664 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000665 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000666 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000667 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000668 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000669 return LI->getPointerOperand();
670 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000671 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000672 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000673 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000674 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000675 return SI->getPointerOperand();
676 }
677 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000678 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000679 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000680 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000681 return RMW->getPointerOperand();
682 }
683 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000684 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000685 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000686 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000687 return XCHG->getPointerOperand();
688 }
Craig Topperf40110f2014-04-25 05:29:35 +0000689 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000690}
691
Kostya Serebryany796f6552014-02-27 12:45:36 +0000692static bool isPointerOperand(Value *V) {
693 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
694}
695
696// This is a rough heuristic; it may cause both false positives and
697// false negatives. The proper implementation requires cooperation with
698// the frontend.
699static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
700 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
701 if (!Cmp->isRelational())
702 return false;
703 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000704 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000705 return false;
706 } else {
707 return false;
708 }
709 if (!isPointerOperand(I->getOperand(0)) ||
710 !isPointerOperand(I->getOperand(1)))
711 return false;
712 return true;
713}
714
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000715bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
716 // If a global variable does not have dynamic initialization we don't
717 // have to instrument it. However, if a global does not have initializer
718 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000719 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000720}
721
Kostya Serebryany796f6552014-02-27 12:45:36 +0000722void
723AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
724 IRBuilder<> IRB(I);
725 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
726 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
727 for (int i = 0; i < 2; i++) {
728 if (Param[i]->getType()->isPointerTy())
729 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
730 }
731 IRB.CreateCall2(F, Param[0], Param[1]);
732}
733
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000734void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000735 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000736 unsigned Alignment = 0;
737 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000738 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000739 if (ClOpt && ClOptGlobals) {
740 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
741 // If initialization order checking is disabled, a simple access to a
742 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000743 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000744 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000745 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000746 }
747 }
748 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
749 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
750 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
751 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
752 NumOptimizedAccessesToGlobalArray++;
753 return;
754 }
755 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000756 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000757 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000758
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000759 Type *OrigPtrTy = Addr->getType();
760 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
761
762 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000763 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000764
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000765 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000766
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000767 if (IsWrite)
768 NumInstrumentedWrites++;
769 else
770 NumInstrumentedReads++;
771
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000772 unsigned Granularity = 1 << Mapping.Scale;
773 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
774 // if the data is properly aligned.
775 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
776 TypeSize == 128) &&
777 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000778 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000779 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000780 // We can not do it with a single check, so we do 1-byte check for the first
781 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
782 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000783 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000784 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000785 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
786 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000787 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000788 } else {
789 Value *LastByte = IRB.CreateIntToPtr(
790 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
791 OrigPtrTy);
792 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
793 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
794 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000795}
796
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000797// Validate the result of Module::getOrInsertFunction called for an interface
798// function of AddressSanitizer. If the instrumented module defines a function
799// with the same name, their prototypes must match, otherwise
800// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000801static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000802 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
803 FuncOrBitcast->dump();
804 report_fatal_error("trying to redefine an AddressSanitizer "
805 "interface function");
806}
807
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000808Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000809 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000810 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000811 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000812 CallInst *Call = SizeArgument
813 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
814 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
815
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000816 // We don't do Call->setDoesNotReturn() because the BB already has
817 // UnreachableInst at the end.
818 // This EmptyAsm is required to avoid callback merge.
819 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000820 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000821}
822
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000823Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000824 Value *ShadowValue,
825 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000826 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000827 // Addr & (Granularity - 1)
828 Value *LastAccessedByte = IRB.CreateAnd(
829 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
830 // (Addr & (Granularity - 1)) + size - 1
831 if (TypeSize / 8 > 1)
832 LastAccessedByte = IRB.CreateAdd(
833 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
834 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
835 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000836 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000837 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
838 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
839}
840
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000841void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000842 Instruction *InsertBefore, Value *Addr,
843 uint32_t TypeSize, bool IsWrite,
844 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000845 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000846 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000847 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
848
849 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000850 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
851 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000852 return;
853 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000854
855 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000856 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000857 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
858 Value *ShadowPtr = memToShadow(AddrLong, IRB);
859 Value *CmpVal = Constant::getNullValue(ShadowTy);
860 Value *ShadowValue = IRB.CreateLoad(
861 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
862
863 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000864 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000865 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000866
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000867 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000868 // We use branch weights for the slow path check, to indicate that the slow
869 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000870 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000871 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
872 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000873 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000874 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000875 IRB.SetInsertPoint(CheckTerm);
876 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000877 BasicBlock *CrashBlock =
878 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000879 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000880 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
881 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000882 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000883 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000884 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000885
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000886 Instruction *Crash = generateCrashCode(
887 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000888 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000889}
890
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000891void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
892 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000893 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000894 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000895
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000896 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000897 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
898 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000899
900 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000901 for (auto &BB : GlobalInit.getBasicBlockList())
902 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000903 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000904}
905
906void AddressSanitizerModule::createInitializerPoisonCalls(
907 Module &M, GlobalValue *ModuleName) {
908 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
909
910 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
911 for (Use &OP : CA->operands()) {
912 if (isa<ConstantAggregateZero>(OP))
913 continue;
914 ConstantStruct *CS = cast<ConstantStruct>(OP);
915
916 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000917 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +0000918 if (F->getName() == kAsanModuleCtorName) continue;
919 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
920 // Don't instrument CTORs that will run before asan.module_ctor.
921 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
922 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000923 }
924 }
925}
926
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000927bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000928 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +0000929 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000930
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000931 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000932 if (!Ty->isSized()) return false;
933 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000934 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000935 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000936 // Don't handle ODR linkage types and COMDATs since other modules may be built
937 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000938 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
939 G->getLinkage() != GlobalVariable::PrivateLinkage &&
940 G->getLinkage() != GlobalVariable::InternalLinkage)
941 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000942 if (G->hasComdat())
943 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000944 // Two problems with thread-locals:
945 // - The address of the main thread's copy can't be computed at link-time.
946 // - Need to poison all copies, not just the main thread's one.
947 if (G->isThreadLocal())
948 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000949 // For now, just ignore this Global if the alignment is large.
950 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000951
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000952 if (G->hasSection()) {
953 StringRef Section(G->getSection());
954 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
955 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
956 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000957 if (Section.startswith("__OBJC,") ||
958 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000959 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000960 return false;
961 }
962 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
963 // Constant CFString instances are compiled in the following way:
964 // -- the string buffer is emitted into
965 // __TEXT,__cstring,cstring_literals
966 // -- the constant NSConstantString structure referencing that buffer
967 // is placed into __DATA,__cfstring
968 // Therefore there's no point in placing redzones into __DATA,__cfstring.
969 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000970 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000971 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
972 return false;
973 }
974 // The linker merges the contents of cstring_literals and removes the
975 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000976 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000977 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000978 return false;
979 }
Rafael Espindolab7a45052014-11-06 20:01:34 +0000980 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
981 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
982 return false;
983 }
984
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000985
986 // Callbacks put into the CRT initializer/terminator sections
987 // should not be instrumented.
988 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
989 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
990 if (Section.startswith(".CRT")) {
991 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
992 return false;
993 }
994
Alexander Potapenko04969e82014-03-20 10:48:34 +0000995 // Globals from llvm.metadata aren't emitted, do not instrument them.
996 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000997 }
998
999 return true;
1000}
1001
Alexey Samsonov788381b2012-12-25 12:28:20 +00001002void AddressSanitizerModule::initializeCallbacks(Module &M) {
1003 IRBuilder<> IRB(*C);
1004 // Declare our poisoning and unpoisoning functions.
1005 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001006 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001007 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1008 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001009 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001010 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1011 // Declare functions that register/unregister globals.
1012 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1013 kAsanRegisterGlobalsName, IRB.getVoidTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001014 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001015 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1016 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1017 kAsanUnregisterGlobalsName,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001018 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001019 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1020}
1021
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001022// This function replaces all global variables with new variables that have
1023// trailing redzones. It also creates a function that poisons
1024// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001025bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001026 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001027
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001028 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1029
Alexey Samsonova02e6642014-05-29 18:40:48 +00001030 for (auto &G : M.globals()) {
1031 if (ShouldInstrumentGlobal(&G))
1032 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001033 }
1034
1035 size_t n = GlobalsToChange.size();
1036 if (n == 0) return false;
1037
1038 // A global is described by a structure
1039 // size_t beg;
1040 // size_t size;
1041 // size_t size_with_redzone;
1042 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001043 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001044 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001045 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001046 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001047 StructType *GlobalStructTy =
1048 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001049 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001050 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001051
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001052 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001053
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001054 // We shouldn't merge same module names, as this string serves as unique
1055 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001056 GlobalVariable *ModuleName = createPrivateGlobalForString(
1057 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001058
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001059 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001060 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001061 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001062
1063 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001064 // Create string holding the global name (use global name from metadata
1065 // if it's available, otherwise just write the name of global variable).
1066 GlobalVariable *Name = createPrivateGlobalForString(
1067 M, MD.Name.empty() ? G->getName() : MD.Name,
1068 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001069
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001070 PointerType *PtrTy = cast<PointerType>(G->getType());
1071 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001072 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001073 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001074 // MinRZ <= RZ <= kMaxGlobalRedzone
1075 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001076 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001077 std::min(kMaxGlobalRedzone,
1078 (SizeInBytes / MinRZ / 4) * MinRZ));
1079 uint64_t RightRedzoneSize = RZ;
1080 // Round up to MinRZ
1081 if (SizeInBytes % MinRZ)
1082 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1083 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001084 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1085
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001086 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001087 Constant *NewInitializer = ConstantStruct::get(
1088 NewTy, G->getInitializer(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001089 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001090
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001091 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001092 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1093 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1094 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001095 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001096 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001097 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001098 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001099 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001100
1101 Value *Indices2[2];
1102 Indices2[0] = IRB.getInt32(0);
1103 Indices2[1] = IRB.getInt32(0);
1104
1105 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001106 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001107 NewGlobal->takeName(G);
1108 G->eraseFromParent();
1109
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001110 Constant *SourceLoc;
1111 if (!MD.SourceLoc.empty()) {
1112 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1113 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1114 } else {
1115 SourceLoc = ConstantInt::get(IntptrTy, 0);
1116 }
1117
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001118 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001119 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001120 ConstantInt::get(IntptrTy, SizeInBytes),
1121 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1122 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001123 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001124 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001125
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001126 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001127 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001128
Kostya Serebryany20343352012-10-17 13:40:06 +00001129 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001130 }
1131
1132 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1133 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001134 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001135 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1136
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001137 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001138 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001139 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001140 IRB.CreateCall2(AsanRegisterGlobals,
1141 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1142 ConstantInt::get(IntptrTy, n));
1143
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001144 // We also need to unregister globals at the end, e.g. when a shared library
1145 // gets closed.
1146 Function *AsanDtorFunction = Function::Create(
1147 FunctionType::get(Type::getVoidTy(*C), false),
1148 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1149 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1150 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001151 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1152 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1153 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001154 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001155
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001156 DEBUG(dbgs() << M);
1157 return true;
1158}
1159
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001160bool AddressSanitizerModule::runOnModule(Module &M) {
1161 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1162 if (!DLP)
1163 return false;
1164 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001165 C = &(M.getContext());
1166 int LongSize = DL->getPointerSizeInBits();
1167 IntptrTy = Type::getIntNTy(*C, LongSize);
1168 Mapping = getShadowMapping(M, LongSize);
1169 initializeCallbacks(M);
1170
1171 bool Changed = false;
1172
1173 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1174 assert(CtorFunc);
1175 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1176
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001177 if (ClGlobals)
1178 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001179
1180 return Changed;
1181}
1182
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001183void AddressSanitizer::initializeCallbacks(Module &M) {
1184 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001185 // Create __asan_report* callbacks.
1186 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1187 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1188 AccessSizeIndex++) {
1189 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001190 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001191 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001192 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001193 checkInterfaceFunction(
1194 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001195 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001196 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1197 checkInterfaceFunction(
1198 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001199 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001200 }
1201 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001202 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001203 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001204 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001205 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001206
Kostya Serebryany86332c02014-04-21 07:10:43 +00001207 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1208 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001209 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001210 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1211 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001212 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001213
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001214 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1215 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001216 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001217 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1218 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001219 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001220 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1221 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001222 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001223
1224 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001225 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001226
Kostya Serebryany796f6552014-02-27 12:45:36 +00001227 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001228 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001229 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001230 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001231 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1232 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1233 StringRef(""), StringRef(""),
1234 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001235}
1236
1237// virtual
1238bool AddressSanitizer::doInitialization(Module &M) {
1239 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001240 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1241 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001242 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001243 DL = &DLP->getDataLayout();
1244
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001245 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001246
1247 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001248 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001249 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001250
1251 AsanCtorFunction = Function::Create(
1252 FunctionType::get(Type::getVoidTy(*C), false),
1253 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1254 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1255 // call __asan_init in the module ctor.
1256 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1257 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001258 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001259 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1260 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001261
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001262 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001263
Alexey Samsonov1f647502014-05-29 01:10:14 +00001264 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001265 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001266}
1267
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001268bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1269 // For each NSObject descendant having a +load method, this method is invoked
1270 // by the ObjC runtime before any of the static constructors is called.
1271 // Therefore we need to instrument such methods with a call to __asan_init
1272 // at the beginning in order to initialize our runtime before any access to
1273 // the shadow memory.
1274 // We cannot just ignore these methods, because they may call other
1275 // instrumented functions.
1276 if (F.getName().find(" load]") != std::string::npos) {
1277 IRBuilder<> IRB(F.begin()->begin());
1278 IRB.CreateCall(AsanInitFunction);
1279 return true;
1280 }
1281 return false;
1282}
1283
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001284bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001285 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001286 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001287 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001288 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001289
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001290 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001291 maybeInsertAsanInitAtFunctionEntry(F);
1292
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001293 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001294 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001295
1296 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1297 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001298
1299 // We want to instrument every address only once per basic block (unless there
1300 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001301 SmallSet<Value*, 16> TempsToInstrument;
1302 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001303 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001304 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001305 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001306 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001307 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001308 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001309
1310 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001311 for (auto &BB : F) {
1312 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001313 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001314 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001315 for (auto &Inst : BB) {
1316 if (LooksLikeCodeInBug11395(&Inst)) return false;
1317 if (Value *Addr =
1318 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001319 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001320 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001321 continue; // We've seen this temp in the current BB.
1322 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001323 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001324 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1325 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001326 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001327 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001328 // ok, take it.
1329 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001330 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001331 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001332 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001333 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001334 // A call inside BB.
1335 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001336 if (CS.doesNotReturn())
1337 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001338 }
1339 continue;
1340 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001341 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001342 NumInsnsPerBB++;
1343 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1344 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001345 }
1346 }
1347
Craig Topperf40110f2014-04-25 05:29:35 +00001348 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001349 bool LikelyToInstrument =
1350 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1351 if (ClKeepUninstrumented && LikelyToInstrument) {
1352 ValueToValueMapTy VMap;
1353 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1354 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1355 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1356 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1357 }
1358
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001359 bool UseCalls = false;
1360 if (ClInstrumentationWithCallsThreshold >= 0 &&
1361 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1362 UseCalls = true;
1363
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001364 // Instrument.
1365 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001366 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001367 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1368 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001369 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001370 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001371 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001372 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001373 }
1374 NumInstrumented++;
1375 }
1376
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001377 FunctionStackPoisoner FSP(F, *this);
1378 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001379
1380 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1381 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001382 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001383 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001384 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001385 }
1386
Alexey Samsonova02e6642014-05-29 18:40:48 +00001387 for (auto Inst : PointerComparisonsOrSubtracts) {
1388 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001389 NumInstrumented++;
1390 }
1391
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001392 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001393
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001394 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1395
1396 if (ClKeepUninstrumented) {
1397 if (!res) {
1398 // No instrumentation is done, no need for the duplicate.
1399 if (UninstrumentedDuplicate)
1400 UninstrumentedDuplicate->eraseFromParent();
1401 } else {
1402 // The function was instrumented. We must have the duplicate.
1403 assert(UninstrumentedDuplicate);
1404 UninstrumentedDuplicate->setSection("NOASAN");
1405 assert(!F.hasSection());
1406 F.setSection("ASAN");
1407 }
1408 }
1409
1410 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001411}
1412
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001413// Workaround for bug 11395: we don't want to instrument stack in functions
1414// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1415// FIXME: remove once the bug 11395 is fixed.
1416bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1417 if (LongSize != 32) return false;
1418 CallInst *CI = dyn_cast<CallInst>(I);
1419 if (!CI || !CI->isInlineAsm()) return false;
1420 if (CI->getNumArgOperands() <= 5) return false;
1421 // We have inline assembly with quite a few arguments.
1422 return true;
1423}
1424
1425void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1426 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001427 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1428 std::string Suffix = itostr(i);
1429 AsanStackMallocFunc[i] = checkInterfaceFunction(
1430 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001431 IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001432 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1433 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001434 IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001435 }
David Blaikiea92765c2014-11-14 00:41:42 +00001436 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1437 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1438 IntptrTy, IntptrTy, nullptr));
1439 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1440 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1441 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001442}
1443
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001444void
Craig Topper3af97222014-08-27 05:25:00 +00001445FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001446 IRBuilder<> &IRB, Value *ShadowBase,
1447 bool DoPoison) {
1448 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001449 size_t i = 0;
1450 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1451 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1452 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1453 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1454 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1455 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1456 uint64_t Val = 0;
1457 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001458 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001459 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1460 else
1461 Val = (Val << 8) | ShadowBytes[i + j];
1462 }
1463 if (!Val) continue;
1464 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1465 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1466 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1467 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001468 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001469 }
1470}
1471
Kostya Serebryany6805de52013-09-10 13:16:56 +00001472// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1473// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1474static int StackMallocSizeClass(uint64_t LocalStackSize) {
1475 assert(LocalStackSize <= kMaxStackMallocSize);
1476 uint64_t MaxSize = kMinStackMallocSize;
1477 for (int i = 0; ; i++, MaxSize *= 2)
1478 if (LocalStackSize <= MaxSize)
1479 return i;
1480 llvm_unreachable("impossible LocalStackSize");
1481}
1482
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001483// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1484// We can not use MemSet intrinsic because it may end up calling the actual
1485// memset. Size is a multiple of 8.
1486// Currently this generates 8-byte stores on x86_64; it may be better to
1487// generate wider stores.
1488void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1489 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1490 assert(!(Size % 8));
1491 assert(kAsanStackAfterReturnMagic == 0xf5);
1492 for (int i = 0; i < Size; i += 8) {
1493 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1494 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1495 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1496 }
1497}
1498
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001499static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001500 for (const auto &Inst : F.getEntryBlock())
1501 if (!isa<AllocaInst>(Inst))
1502 return Inst.getDebugLoc();
1503 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001504}
1505
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001506void FunctionStackPoisoner::poisonStack() {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001507 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001508 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001509
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001510 assert(AllocaVec.size() > 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001511 Instruction *InsBefore = AllocaVec[0];
1512 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001513 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001514
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001515 SmallVector<ASanStackVariableDescription, 16> SVD;
1516 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001517 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001518 ASanStackVariableDescription D = { AI->getName().data(),
1519 getAllocaSizeInBytes(AI),
1520 AI->getAlignment(), AI, 0};
1521 SVD.push_back(D);
1522 }
1523 // Minimal header size (left redzone) is 4 pointers,
1524 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1525 size_t MinHeaderSize = ASan.LongSize / 2;
1526 ASanStackFrameLayout L;
1527 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1528 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1529 uint64_t LocalStackSize = L.FrameSize;
1530 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001531 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001532
1533 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1534 AllocaInst *MyAlloca =
1535 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001536 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001537 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1538 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1539 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001540 assert(MyAlloca->isStaticAlloca());
1541 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1542 Value *LocalStackBase = OrigStackBase;
1543
1544 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001545 // LocalStackBase = OrigStackBase
1546 // if (__asan_option_detect_stack_use_after_return)
1547 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001548 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1549 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001550 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1551 kAsanOptionDetectUAR, IRB.getInt32Ty());
1552 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1553 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001554 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001555 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1556 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001557 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001558 LocalStackBase = IRBIf.CreateCall2(
1559 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001560 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001561 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1562 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001563 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001564 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1565 Phi->addIncoming(OrigStackBase, CmpBlock);
1566 Phi->addIncoming(LocalStackBase, SetBlock);
1567 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001568 }
1569
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001570 // Insert poison calls for lifetime intrinsics for alloca.
1571 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001572 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001573 assert(APC.InsBefore);
1574 assert(APC.AI);
1575 IRBuilder<> IRB(APC.InsBefore);
1576 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001577 HavePoisonedAllocas |= APC.DoPoison;
1578 }
1579
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001580 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001581 for (const auto &Desc : SVD) {
1582 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001583 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001584 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001585 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001586 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001587 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001588 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001589
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001590 // The left-most redzone has enough space for at least 4 pointers.
1591 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001592 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1593 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1594 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001595 // Write the frame description constant to redzone[1].
1596 Value *BasePlus1 = IRB.CreateIntToPtr(
1597 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1598 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001599 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001600 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1601 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001602 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1603 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001604 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001605 // Write the PC to redzone[2].
1606 Value *BasePlus2 = IRB.CreateIntToPtr(
1607 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1608 2 * ASan.LongSize/8)),
1609 IntptrPtrTy);
1610 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001611
1612 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001613 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001614 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001615
Kostya Serebryany530e2072013-12-23 14:15:08 +00001616 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001617 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001618 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001619 // Mark the current frame as retired.
1620 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1621 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001622 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001623 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001624 // if LocalStackBase != OrigStackBase:
1625 // // In use-after-return mode, poison the whole stack frame.
1626 // if StackMallocIdx <= 4
1627 // // For small sizes inline the whole thing:
1628 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1629 // **SavedFlagPtr(LocalStackBase) = 0
1630 // else
1631 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1632 // else
1633 // <This is not a fake stack; unpoison the redzones>
1634 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1635 TerminatorInst *ThenTerm, *ElseTerm;
1636 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1637
1638 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001639 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001640 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1641 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1642 ClassSize >> Mapping.Scale);
1643 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1644 LocalStackBase,
1645 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1646 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1647 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1648 IRBPoison.CreateStore(
1649 Constant::getNullValue(IRBPoison.getInt8Ty()),
1650 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1651 } else {
1652 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001653 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1654 ConstantInt::get(IntptrTy, LocalStackSize),
1655 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001656 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001657
1658 IRBuilder<> IRBElse(ElseTerm);
1659 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001660 } else if (HavePoisonedAllocas) {
1661 // If we poisoned some allocas in llvm.lifetime analysis,
1662 // unpoison whole stack frame now.
1663 assert(LocalStackBase == OrigStackBase);
1664 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001665 } else {
1666 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001667 }
1668 }
1669
Kostya Serebryany09959942012-10-19 06:20:53 +00001670 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001671 for (auto AI : AllocaVec)
1672 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001673}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001674
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001675void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001676 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001677 // For now just insert the call to ASan runtime.
1678 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1679 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1680 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1681 : AsanUnpoisonStackMemoryFunc,
1682 AddrArg, SizeArg);
1683}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001684
1685// Handling llvm.lifetime intrinsics for a given %alloca:
1686// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1687// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1688// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1689// could be poisoned by previous llvm.lifetime.end instruction, as the
1690// variable may go in and out of scope several times, e.g. in loops).
1691// (3) if we poisoned at least one %alloca in a function,
1692// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001693
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001694AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1695 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1696 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001697 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001698 // See if we've already calculated (or started to calculate) alloca for a
1699 // given value.
1700 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1701 if (I != AllocaForValue.end())
1702 return I->second;
1703 // Store 0 while we're calculating alloca for value V to avoid
1704 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001705 AllocaForValue[V] = nullptr;
1706 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001707 if (CastInst *CI = dyn_cast<CastInst>(V))
1708 Res = findAllocaForValue(CI->getOperand(0));
1709 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1710 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1711 Value *IncValue = PN->getIncomingValue(i);
1712 // Allow self-referencing phi-nodes.
1713 if (IncValue == PN) continue;
1714 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1715 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001716 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1717 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001718 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001719 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001720 }
Craig Topperf40110f2014-04-25 05:29:35 +00001721 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001722 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001723 return Res;
1724}