blob: c3bc1e8ba83a1f43c80096ce0b1a60bcfe8457f6 [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 Serebryany8baa3862014-02-10 07:37:04 +000064static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
65static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066
Kostya Serebryany6805de52013-09-10 13:16:56 +000067static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000068static const size_t kMaxStackMallocSize = 1 << 16; // 64K
69static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
70static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
71
Craig Topperd3a34f82013-07-16 01:17:10 +000072static const char *const kAsanModuleCtorName = "asan.module_ctor";
73static const char *const kAsanModuleDtorName = "asan.module_dtor";
Kostya Serebryany34ddf872014-09-24 22:41:55 +000074static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000075static const char *const kAsanReportErrorTemplate = "__asan_report_";
76static const char *const kAsanReportLoadN = "__asan_report_load_n";
77static const char *const kAsanReportStoreN = "__asan_report_store_n";
78static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000079static const char *const kAsanUnregisterGlobalsName =
80 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000081static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
82static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000083static const char *const kAsanInitName = "__asan_init_v4";
Kostya Serebryany796f6552014-02-27 12:45:36 +000084static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
85static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000086static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000087static const int kMaxAsanStackMallocSizeClass = 10;
88static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
89static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanGenPrefix = "__asan_gen_";
91static const char *const kAsanPoisonStackMemoryName =
92 "__asan_poison_stack_memory";
93static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000094 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000095
Kostya Serebryanyf3223822013-09-18 14:07:14 +000096static const char *const kAsanOptionDetectUAR =
97 "__asan_option_detect_stack_use_after_return";
98
David Blaikieeacc2872013-09-18 00:11:27 +000099#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000100static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000101#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000102
Kostya Serebryany874dae62012-07-16 16:15:40 +0000103// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
104static const size_t kNumberOfAccessSizes = 5;
105
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000106// Command-line flags.
107
108// This flag may need to be replaced with -f[no-]asan-reads.
109static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
110 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
111static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
112 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000113static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
114 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
115 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000116static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
117 cl::desc("use instrumentation with slow path for all accesses"),
118 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000119// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000120// in any given BB. Normally, this should be set to unlimited (INT_MAX),
121// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
122// set it to 10000.
123static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
124 cl::init(10000),
125 cl::desc("maximal number of instructions to instrument in any given BB"),
126 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000127// This flag may need to be replaced with -f[no]asan-stack.
128static cl::opt<bool> ClStack("asan-stack",
129 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000130static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000131 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000132// This flag may need to be replaced with -f[no]asan-globals.
133static cl::opt<bool> ClGlobals("asan-globals",
134 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000135static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000136 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000137static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
138 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000139 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000140static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
141 cl::desc("Realign stack to the value of this flag (power of two)"),
142 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000143static cl::opt<int> ClInstrumentationWithCallsThreshold(
144 "asan-instrumentation-with-call-threshold",
145 cl::desc("If the function being instrumented contains more than "
146 "this number of memory accesses, use callbacks instead of "
147 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000148 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000149static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
150 "asan-memory-access-callback-prefix",
151 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
152 cl::init("__asan_"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000153
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000154// This is an experimental feature that will allow to choose between
155// instrumented and non-instrumented code at link-time.
156// If this option is on, just before instrumenting a function we create its
157// clone; if the function is not changed by asan the clone is deleted.
158// If we end up with a clone, we put the instrumented function into a section
159// called "ASAN" and the uninstrumented function into a section called "NOASAN".
160//
161// This is still a prototype, we need to figure out a way to keep two copies of
162// a function so that the linker can easily choose one of them.
163static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
164 cl::desc("Keep uninstrumented copies of functions"),
165 cl::Hidden, cl::init(false));
166
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000167// These flags allow to change the shadow mapping.
168// The shadow mapping looks like
169// Shadow = (Mem >> scale) + (1 << offset_log)
170static cl::opt<int> ClMappingScale("asan-mapping-scale",
171 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000172
173// Optimization flags. Not user visible, used mostly for testing
174// and benchmarking the tool.
175static cl::opt<bool> ClOpt("asan-opt",
176 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
177static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
178 cl::desc("Instrument the same temp just once"), cl::Hidden,
179 cl::init(true));
180static cl::opt<bool> ClOptGlobals("asan-opt-globals",
181 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
182
Alexey Samsonovdf624522012-11-29 18:14:24 +0000183static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
184 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
185 cl::Hidden, cl::init(false));
186
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000187// Debug flags.
188static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
189 cl::init(0));
190static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
191 cl::Hidden, cl::init(0));
192static cl::opt<std::string> ClDebugFunc("asan-debug-func",
193 cl::Hidden, cl::desc("Debug func"));
194static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
195 cl::Hidden, cl::init(-1));
196static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
197 cl::Hidden, cl::init(-1));
198
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000199STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
200STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
201STATISTIC(NumOptimizedAccessesToGlobalArray,
202 "Number of optimized accesses to global arrays");
203STATISTIC(NumOptimizedAccessesToGlobalVar,
204 "Number of optimized accesses to global vars");
205
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000206namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000207/// Frontend-provided metadata for source location.
208struct LocationMetadata {
209 StringRef Filename;
210 int LineNo;
211 int ColumnNo;
212
213 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
214
215 bool empty() const { return Filename.empty(); }
216
217 void parse(MDNode *MDN) {
218 assert(MDN->getNumOperands() == 3);
219 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
220 Filename = MDFilename->getString();
221 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
222 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
223 }
224};
225
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000226/// Frontend-provided metadata for global variables.
227class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000228 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000229 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000230 Entry()
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000231 : SourceLoc(), Name(), IsDynInit(false),
Alexey Samsonov15c96692014-07-12 00:42:52 +0000232 IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000233 LocationMetadata SourceLoc;
234 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000235 bool IsDynInit;
236 bool IsBlacklisted;
237 };
238
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000239 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000240
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000241 void init(Module& M) {
242 assert(!inited_);
243 inited_ = true;
244 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
245 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000246 return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000247 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000248 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000249 assert(MDN->getNumOperands() == 5);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000250 Value *V = MDN->getOperand(0);
251 // The optimizer may optimize away a global entirely.
252 if (!V)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000253 continue;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000254 GlobalVariable *GV = cast<GlobalVariable>(V);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000255 // We can already have an entry for GV if it was merged with another
256 // global.
257 Entry &E = Entries[GV];
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000258 if (Value *Loc = MDN->getOperand(1))
259 E.SourceLoc.parse(cast<MDNode>(Loc));
Alexey Samsonov15c96692014-07-12 00:42:52 +0000260 if (Value *Name = MDN->getOperand(2)) {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000261 MDString *MDName = cast<MDString>(Name);
262 E.Name = MDName->getString();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000263 }
264 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000265 E.IsDynInit |= IsDynInit->isOne();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000266 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000267 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000268 }
269 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000270
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000271 /// Returns metadata entry for a given global.
272 Entry get(GlobalVariable *G) const {
273 auto Pos = Entries.find(G);
274 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000275 }
276
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000277 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000278 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000279 DenseMap<GlobalVariable*, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000280};
281
Alexey Samsonov1345d352013-01-16 13:23:28 +0000282/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000283/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000284struct ShadowMapping {
285 int Scale;
286 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000287 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000288};
289
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000290static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000291 llvm::Triple TargetTriple(M.getTargetTriple());
292 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000293 bool IsIOS = TargetTriple.isiOS();
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000294 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000295 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000296 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
297 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000298 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000299 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
300 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000301
302 ShadowMapping Mapping;
303
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000304 if (LongSize == 32) {
305 if (IsAndroid)
306 Mapping.Offset = 0;
307 else if (IsMIPS32)
308 Mapping.Offset = kMIPS32_ShadowOffset32;
309 else if (IsFreeBSD)
310 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000311 else if (IsIOS)
312 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000313 else
314 Mapping.Offset = kDefaultShadowOffset32;
315 } else { // LongSize == 64
316 if (IsPPC64)
317 Mapping.Offset = kPPC64_ShadowOffset64;
318 else if (IsFreeBSD)
319 Mapping.Offset = kFreeBSD_ShadowOffset64;
320 else if (IsLinux && IsX86_64)
321 Mapping.Offset = kSmallX86_64ShadowOffset;
322 else
323 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000324 }
325
326 Mapping.Scale = kDefaultShadowScale;
327 if (ClMappingScale) {
328 Mapping.Scale = ClMappingScale;
329 }
330
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000331 // OR-ing shadow offset if more efficient (at least on x86) if the offset
332 // is a power of two, but on ppc64 we have to use add since the shadow
333 // offset is not necessary 1/8-th of the address space.
334 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
335
Alexey Samsonov1345d352013-01-16 13:23:28 +0000336 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000337}
338
Alexey Samsonov1345d352013-01-16 13:23:28 +0000339static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000340 // Redzone used for stack and globals is at least 32 bytes.
341 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000342 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000343}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000344
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000345/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000346struct AddressSanitizer : public FunctionPass {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000347 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000348 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000349 return "AddressSanitizerFunctionPass";
350 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000351 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000352 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000353 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
354 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000355 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000356 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
357 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000358 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000359 bool IsWrite, size_t AccessSizeIndex,
360 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000361 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000362 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000363 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000364 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000365 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000366 static char ID; // Pass identification, replacement for typeid
367
368 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000369 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000370
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000371 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000372 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000373
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000374 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000375 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000376 int LongSize;
377 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000378 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000379 Function *AsanCtorFunction;
380 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000381 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000382 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000383 // This array is indexed by AccessIsWrite and log2(AccessSize).
384 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000385 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000386 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000387 Function *AsanErrorCallbackSized[2],
388 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000389 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000390 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000391 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000392
393 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000394};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000395
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000396class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000397 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000398 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000399 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000400 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000401 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000402 return "AddressSanitizerModule";
403 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000404
Kostya Serebryany20a79972012-11-22 03:18:50 +0000405 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000406 void initializeCallbacks(Module &M);
407
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000408 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000409 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000410 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000411 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000412 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000413 return RedzoneSizeForScale(Mapping.Scale);
414 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000415
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000416 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000417 Type *IntptrTy;
418 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000419 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000420 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000421 Function *AsanPoisonGlobals;
422 Function *AsanUnpoisonGlobals;
423 Function *AsanRegisterGlobals;
424 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000425};
426
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000427// Stack poisoning does not play well with exception handling.
428// When an exception is thrown, we essentially bypass the code
429// that unpoisones the stack. This is why the run-time library has
430// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
431// stack in the interceptor. This however does not work inside the
432// actual function which catches the exception. Most likely because the
433// compiler hoists the load of the shadow value somewhere too high.
434// This causes asan to report a non-existing bug on 453.povray.
435// It sounds like an LLVM bug.
436struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
437 Function &F;
438 AddressSanitizer &ASan;
439 DIBuilder DIB;
440 LLVMContext *C;
441 Type *IntptrTy;
442 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000443 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000444
445 SmallVector<AllocaInst*, 16> AllocaVec;
446 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000447 unsigned StackAlignment;
448
Kostya Serebryany6805de52013-09-10 13:16:56 +0000449 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
450 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000451 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
452
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000453 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
454 struct AllocaPoisonCall {
455 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000456 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000457 uint64_t Size;
458 bool DoPoison;
459 };
460 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
461
462 // Maps Value to an AllocaInst from which the Value is originated.
463 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
464 AllocaForValueMapTy AllocaForValue;
465
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000466 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
467 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
468 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000469 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000470 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000471
472 bool runOnFunction() {
473 if (!ClStack) return false;
474 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000475 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000476 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000477
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000478 if (AllocaVec.empty()) return false;
479
480 initializeCallbacks(*F.getParent());
481
482 poisonStack();
483
484 if (ClDebugStack) {
485 DEBUG(dbgs() << F);
486 }
487 return true;
488 }
489
490 // Finds all static Alloca instructions and puts
491 // poisoned red zones around all of them.
492 // Then unpoison everything back before the function returns.
493 void poisonStack();
494
495 // ----------------------- Visitors.
496 /// \brief Collect all Ret instructions.
497 void visitReturnInst(ReturnInst &RI) {
498 RetVec.push_back(&RI);
499 }
500
501 /// \brief Collect Alloca instructions we want (and can) handle.
502 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000503 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000504
505 StackAlignment = std::max(StackAlignment, AI.getAlignment());
506 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000507 }
508
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000509 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
510 /// errors.
511 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000512 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000513 Intrinsic::ID ID = II.getIntrinsicID();
514 if (ID != Intrinsic::lifetime_start &&
515 ID != Intrinsic::lifetime_end)
516 return;
517 // Found lifetime intrinsic, add ASan instrumentation if necessary.
518 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
519 // If size argument is undefined, don't do anything.
520 if (Size->isMinusOne()) return;
521 // Check that size doesn't saturate uint64_t and can
522 // be stored in IntptrTy.
523 const uint64_t SizeValue = Size->getValue().getLimitedValue();
524 if (SizeValue == ~0ULL ||
525 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
526 return;
527 // Find alloca instruction that corresponds to llvm.lifetime argument.
528 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
529 if (!AI) return;
530 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000531 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000532 AllocaPoisonCallVec.push_back(APC);
533 }
534
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000535 // ---------------------- Helpers.
536 void initializeCallbacks(Module &M);
537
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000538 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000539 bool isInterestingAlloca(AllocaInst &AI) const {
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000540 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
541 AI.getAllocatedType()->isSized() &&
542 // alloca() may be called with 0 size, ignore it.
543 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000544 }
545
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000546 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000547 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000548 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000549 return SizeInBytes;
550 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000551 /// Finds alloca where the value comes from.
552 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000553 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000554 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000555 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000556
557 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
558 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000559};
560
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000561} // namespace
562
563char AddressSanitizer::ID = 0;
564INITIALIZE_PASS(AddressSanitizer, "asan",
565 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
566 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000567FunctionPass *llvm::createAddressSanitizerFunctionPass() {
568 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000569}
570
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000571char AddressSanitizerModule::ID = 0;
572INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
573 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
574 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000575ModulePass *llvm::createAddressSanitizerModulePass() {
576 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000577}
578
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000579static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000580 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000581 assert(Res < kNumberOfAccessSizes);
582 return Res;
583}
584
Bill Wendling58f8cef2013-08-06 22:52:42 +0000585// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000586static GlobalVariable *createPrivateGlobalForString(
587 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000588 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000589 // We use private linkage for module-local strings. If they can be merged
590 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000591 GlobalVariable *GV =
592 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000593 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
594 if (AllowMerging)
595 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000596 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
597 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000598}
599
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000600/// \brief Create a global describing a source location.
601static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
602 LocationMetadata MD) {
603 Constant *LocData[] = {
604 createPrivateGlobalForString(M, MD.Filename, true),
605 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
606 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
607 };
608 auto LocStruct = ConstantStruct::getAnon(LocData);
609 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
610 GlobalValue::PrivateLinkage, LocStruct,
611 kAsanGenPrefix);
612 GV->setUnnamedAddr(true);
613 return GV;
614}
615
Kostya Serebryany139a9372012-11-20 14:16:08 +0000616static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
617 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000618}
619
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000620Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
621 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000622 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
623 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000624 return Shadow;
625 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000626 if (Mapping.OrShadowOffset)
627 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
628 else
629 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000630}
631
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000632// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000633void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
634 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000635 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000636 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000637 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
638 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
639 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
640 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
641 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000642 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000643 AsanMemset,
644 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
645 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
646 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000647 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000648 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000649}
650
Kostya Serebryany90241602012-05-30 09:04:06 +0000651// If I is an interesting memory access, return the PointerOperand
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000652// and set IsWrite/Alignment. Otherwise return NULL.
653static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
654 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000655 // Skip memory accesses inserted by another instrumentation.
656 if (I->getMetadata("nosanitize"))
657 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000658 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000659 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000660 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000661 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000662 return LI->getPointerOperand();
663 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000664 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000665 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000666 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000667 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000668 return SI->getPointerOperand();
669 }
670 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000671 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000672 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000673 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000674 return RMW->getPointerOperand();
675 }
676 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000677 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000678 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000679 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000680 return XCHG->getPointerOperand();
681 }
Craig Topperf40110f2014-04-25 05:29:35 +0000682 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000683}
684
Kostya Serebryany796f6552014-02-27 12:45:36 +0000685static bool isPointerOperand(Value *V) {
686 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
687}
688
689// This is a rough heuristic; it may cause both false positives and
690// false negatives. The proper implementation requires cooperation with
691// the frontend.
692static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
693 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
694 if (!Cmp->isRelational())
695 return false;
696 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000697 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000698 return false;
699 } else {
700 return false;
701 }
702 if (!isPointerOperand(I->getOperand(0)) ||
703 !isPointerOperand(I->getOperand(1)))
704 return false;
705 return true;
706}
707
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000708bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
709 // If a global variable does not have dynamic initialization we don't
710 // have to instrument it. However, if a global does not have initializer
711 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000712 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000713}
714
Kostya Serebryany796f6552014-02-27 12:45:36 +0000715void
716AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
717 IRBuilder<> IRB(I);
718 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
719 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
720 for (int i = 0; i < 2; i++) {
721 if (Param[i]->getType()->isPointerTy())
722 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
723 }
724 IRB.CreateCall2(F, Param[0], Param[1]);
725}
726
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000727void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000728 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000729 unsigned Alignment = 0;
730 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000731 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000732 if (ClOpt && ClOptGlobals) {
733 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
734 // If initialization order checking is disabled, a simple access to a
735 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000736 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000737 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000738 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000739 }
740 }
741 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
742 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
743 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
744 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
745 NumOptimizedAccessesToGlobalArray++;
746 return;
747 }
748 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000749 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000750 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000751
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000752 Type *OrigPtrTy = Addr->getType();
753 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
754
755 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000756 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000757
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000758 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000759
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000760 if (IsWrite)
761 NumInstrumentedWrites++;
762 else
763 NumInstrumentedReads++;
764
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000765 unsigned Granularity = 1 << Mapping.Scale;
766 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
767 // if the data is properly aligned.
768 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
769 TypeSize == 128) &&
770 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000771 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000772 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000773 // We can not do it with a single check, so we do 1-byte check for the first
774 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
775 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000776 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000777 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000778 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
779 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000780 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000781 } else {
782 Value *LastByte = IRB.CreateIntToPtr(
783 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
784 OrigPtrTy);
785 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
786 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
787 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000788}
789
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000790// Validate the result of Module::getOrInsertFunction called for an interface
791// function of AddressSanitizer. If the instrumented module defines a function
792// with the same name, their prototypes must match, otherwise
793// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000794static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000795 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
796 FuncOrBitcast->dump();
797 report_fatal_error("trying to redefine an AddressSanitizer "
798 "interface function");
799}
800
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000801Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000802 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000803 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000804 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000805 CallInst *Call = SizeArgument
806 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
807 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
808
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000809 // We don't do Call->setDoesNotReturn() because the BB already has
810 // UnreachableInst at the end.
811 // This EmptyAsm is required to avoid callback merge.
812 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000813 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000814}
815
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000816Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000817 Value *ShadowValue,
818 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000819 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000820 // Addr & (Granularity - 1)
821 Value *LastAccessedByte = IRB.CreateAnd(
822 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
823 // (Addr & (Granularity - 1)) + size - 1
824 if (TypeSize / 8 > 1)
825 LastAccessedByte = IRB.CreateAdd(
826 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
827 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
828 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000829 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000830 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
831 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
832}
833
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000834void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000835 Instruction *InsertBefore, Value *Addr,
836 uint32_t TypeSize, bool IsWrite,
837 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000838 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000839 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000840 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
841
842 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000843 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
844 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000845 return;
846 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000847
848 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000849 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000850 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
851 Value *ShadowPtr = memToShadow(AddrLong, IRB);
852 Value *CmpVal = Constant::getNullValue(ShadowTy);
853 Value *ShadowValue = IRB.CreateLoad(
854 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
855
856 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000857 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000858 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000859
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000860 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +0000861 // We use branch weights for the slow path check, to indicate that the slow
862 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000863 TerminatorInst *CheckTerm =
Kostya Serebryanyad238522014-09-02 21:46:51 +0000864 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
865 MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000866 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000867 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000868 IRB.SetInsertPoint(CheckTerm);
869 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000870 BasicBlock *CrashBlock =
871 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000872 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000873 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
874 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000875 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000876 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000877 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000878
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000879 Instruction *Crash = generateCrashCode(
880 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000881 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000882}
883
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000884void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
885 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000886 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000887 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000888
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000889 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000890 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
891 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000892
893 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000894 for (auto &BB : GlobalInit.getBasicBlockList())
895 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000896 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000897}
898
899void AddressSanitizerModule::createInitializerPoisonCalls(
900 Module &M, GlobalValue *ModuleName) {
901 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
902
903 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
904 for (Use &OP : CA->operands()) {
905 if (isa<ConstantAggregateZero>(OP))
906 continue;
907 ConstantStruct *CS = cast<ConstantStruct>(OP);
908
909 // Must have a function or null ptr.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000910 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +0000911 if (F->getName() == kAsanModuleCtorName) continue;
912 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
913 // Don't instrument CTORs that will run before asan.module_ctor.
914 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
915 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000916 }
917 }
918}
919
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000920bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000921 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +0000922 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000923
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000924 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000925 if (!Ty->isSized()) return false;
926 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000927 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000928 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000929 // Don't handle ODR linkage types and COMDATs since other modules may be built
930 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000931 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
932 G->getLinkage() != GlobalVariable::PrivateLinkage &&
933 G->getLinkage() != GlobalVariable::InternalLinkage)
934 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000935 if (G->hasComdat())
936 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000937 // Two problems with thread-locals:
938 // - The address of the main thread's copy can't be computed at link-time.
939 // - Need to poison all copies, not just the main thread's one.
940 if (G->isThreadLocal())
941 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000942 // For now, just ignore this Global if the alignment is large.
943 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000944
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000945 if (G->hasSection()) {
946 StringRef Section(G->getSection());
947 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
948 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
949 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000950 if (Section.startswith("__OBJC,") ||
951 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000952 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000953 return false;
954 }
955 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
956 // Constant CFString instances are compiled in the following way:
957 // -- the string buffer is emitted into
958 // __TEXT,__cstring,cstring_literals
959 // -- the constant NSConstantString structure referencing that buffer
960 // is placed into __DATA,__cfstring
961 // Therefore there's no point in placing redzones into __DATA,__cfstring.
962 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000963 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000964 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
965 return false;
966 }
967 // The linker merges the contents of cstring_literals and removes the
968 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000969 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000970 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000971 return false;
972 }
Rafael Espindolab7a45052014-11-06 20:01:34 +0000973 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
974 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
975 return false;
976 }
977
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000978
979 // Callbacks put into the CRT initializer/terminator sections
980 // should not be instrumented.
981 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
982 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
983 if (Section.startswith(".CRT")) {
984 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
985 return false;
986 }
987
Alexander Potapenko04969e82014-03-20 10:48:34 +0000988 // Globals from llvm.metadata aren't emitted, do not instrument them.
989 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000990 }
991
992 return true;
993}
994
Alexey Samsonov788381b2012-12-25 12:28:20 +0000995void AddressSanitizerModule::initializeCallbacks(Module &M) {
996 IRBuilder<> IRB(*C);
997 // Declare our poisoning and unpoisoning functions.
998 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000999 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001000 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1001 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1002 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1003 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1004 // Declare functions that register/unregister globals.
1005 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1006 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1007 IntptrTy, IntptrTy, NULL));
1008 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1009 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1010 kAsanUnregisterGlobalsName,
1011 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1012 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1013}
1014
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001015// This function replaces all global variables with new variables that have
1016// trailing redzones. It also creates a function that poisons
1017// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001018bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001019 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001020
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001021 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1022
Alexey Samsonova02e6642014-05-29 18:40:48 +00001023 for (auto &G : M.globals()) {
1024 if (ShouldInstrumentGlobal(&G))
1025 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001026 }
1027
1028 size_t n = GlobalsToChange.size();
1029 if (n == 0) return false;
1030
1031 // A global is described by a structure
1032 // size_t beg;
1033 // size_t size;
1034 // size_t size_with_redzone;
1035 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001036 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001037 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001038 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001039 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001040 StructType *GlobalStructTy =
1041 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1042 IntptrTy, IntptrTy, NULL);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001043 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001044
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001045 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001046
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001047 // We shouldn't merge same module names, as this string serves as unique
1048 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001049 GlobalVariable *ModuleName = createPrivateGlobalForString(
1050 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001051
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001052 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001053 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001054 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001055
1056 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001057 // Create string holding the global name (use global name from metadata
1058 // if it's available, otherwise just write the name of global variable).
1059 GlobalVariable *Name = createPrivateGlobalForString(
1060 M, MD.Name.empty() ? G->getName() : MD.Name,
1061 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001062
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001063 PointerType *PtrTy = cast<PointerType>(G->getType());
1064 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001065 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001066 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001067 // MinRZ <= RZ <= kMaxGlobalRedzone
1068 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001069 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001070 std::min(kMaxGlobalRedzone,
1071 (SizeInBytes / MinRZ / 4) * MinRZ));
1072 uint64_t RightRedzoneSize = RZ;
1073 // Round up to MinRZ
1074 if (SizeInBytes % MinRZ)
1075 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1076 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001077 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1078
1079 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1080 Constant *NewInitializer = ConstantStruct::get(
1081 NewTy, G->getInitializer(),
1082 Constant::getNullValue(RightRedZoneTy), NULL);
1083
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001084 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001085 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1086 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1087 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001088 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001089 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001090 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001091 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001092 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001093
1094 Value *Indices2[2];
1095 Indices2[0] = IRB.getInt32(0);
1096 Indices2[1] = IRB.getInt32(0);
1097
1098 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001099 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001100 NewGlobal->takeName(G);
1101 G->eraseFromParent();
1102
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001103 Constant *SourceLoc;
1104 if (!MD.SourceLoc.empty()) {
1105 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1106 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1107 } else {
1108 SourceLoc = ConstantInt::get(IntptrTy, 0);
1109 }
1110
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001111 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001112 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001113 ConstantInt::get(IntptrTy, SizeInBytes),
1114 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1115 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001116 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001117 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, NULL);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001118
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001119 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001120 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001121
Kostya Serebryany20343352012-10-17 13:40:06 +00001122 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001123 }
1124
1125 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1126 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001127 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001128 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1129
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001130 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001131 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001132 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001133 IRB.CreateCall2(AsanRegisterGlobals,
1134 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1135 ConstantInt::get(IntptrTy, n));
1136
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001137 // We also need to unregister globals at the end, e.g. when a shared library
1138 // gets closed.
1139 Function *AsanDtorFunction = Function::Create(
1140 FunctionType::get(Type::getVoidTy(*C), false),
1141 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1142 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1143 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001144 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1145 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1146 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001147 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001148
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001149 DEBUG(dbgs() << M);
1150 return true;
1151}
1152
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001153bool AddressSanitizerModule::runOnModule(Module &M) {
1154 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1155 if (!DLP)
1156 return false;
1157 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001158 C = &(M.getContext());
1159 int LongSize = DL->getPointerSizeInBits();
1160 IntptrTy = Type::getIntNTy(*C, LongSize);
1161 Mapping = getShadowMapping(M, LongSize);
1162 initializeCallbacks(M);
1163
1164 bool Changed = false;
1165
1166 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1167 assert(CtorFunc);
1168 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1169
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001170 if (ClGlobals)
1171 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001172
1173 return Changed;
1174}
1175
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001176void AddressSanitizer::initializeCallbacks(Module &M) {
1177 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001178 // Create __asan_report* callbacks.
1179 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1180 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1181 AccessSizeIndex++) {
1182 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001183 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001184 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001185 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001186 checkInterfaceFunction(
1187 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1188 IRB.getVoidTy(), IntptrTy, NULL));
1189 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1190 checkInterfaceFunction(
1191 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1192 IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001193 }
1194 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001195 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1196 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1197 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1198 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001199
Kostya Serebryany86332c02014-04-21 07:10:43 +00001200 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1201 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1202 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1203 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1204 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1205 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1206
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001207 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1208 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1209 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1210 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1211 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1212 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1213 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1214 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1215 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1216
1217 AsanHandleNoReturnFunc = checkInterfaceFunction(
1218 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001219
Kostya Serebryany796f6552014-02-27 12:45:36 +00001220 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1221 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1222 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1223 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001224 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1225 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1226 StringRef(""), StringRef(""),
1227 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001228}
1229
1230// virtual
1231bool AddressSanitizer::doInitialization(Module &M) {
1232 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001233 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1234 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001235 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001236 DL = &DLP->getDataLayout();
1237
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001238 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001239
1240 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001241 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001242 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001243
1244 AsanCtorFunction = Function::Create(
1245 FunctionType::get(Type::getVoidTy(*C), false),
1246 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1247 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1248 // call __asan_init in the module ctor.
1249 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1250 AsanInitFunction = checkInterfaceFunction(
1251 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1252 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1253 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001254
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001255 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001256
Alexey Samsonov1f647502014-05-29 01:10:14 +00001257 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001258 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001259}
1260
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001261bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1262 // For each NSObject descendant having a +load method, this method is invoked
1263 // by the ObjC runtime before any of the static constructors is called.
1264 // Therefore we need to instrument such methods with a call to __asan_init
1265 // at the beginning in order to initialize our runtime before any access to
1266 // the shadow memory.
1267 // We cannot just ignore these methods, because they may call other
1268 // instrumented functions.
1269 if (F.getName().find(" load]") != std::string::npos) {
1270 IRBuilder<> IRB(F.begin()->begin());
1271 IRB.CreateCall(AsanInitFunction);
1272 return true;
1273 }
1274 return false;
1275}
1276
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001277bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001278 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001279 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001280 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001281 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001282
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001283 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001284 maybeInsertAsanInitAtFunctionEntry(F);
1285
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001286 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001287 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001288
1289 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1290 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001291
1292 // We want to instrument every address only once per basic block (unless there
1293 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001294 SmallSet<Value*, 16> TempsToInstrument;
1295 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001296 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001297 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001298 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001299 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001300 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001301 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001302
1303 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001304 for (auto &BB : F) {
1305 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001306 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001307 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001308 for (auto &Inst : BB) {
1309 if (LooksLikeCodeInBug11395(&Inst)) return false;
1310 if (Value *Addr =
1311 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001312 if (ClOpt && ClOptSameTemp) {
1313 if (!TempsToInstrument.insert(Addr))
1314 continue; // We've seen this temp in the current BB.
1315 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001316 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001317 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1318 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001319 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001320 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001321 // ok, take it.
1322 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001323 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001324 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001325 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001326 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001327 // A call inside BB.
1328 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001329 if (CS.doesNotReturn())
1330 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001331 }
1332 continue;
1333 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001334 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001335 NumInsnsPerBB++;
1336 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1337 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001338 }
1339 }
1340
Craig Topperf40110f2014-04-25 05:29:35 +00001341 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001342 bool LikelyToInstrument =
1343 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1344 if (ClKeepUninstrumented && LikelyToInstrument) {
1345 ValueToValueMapTy VMap;
1346 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1347 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1348 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1349 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1350 }
1351
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001352 bool UseCalls = false;
1353 if (ClInstrumentationWithCallsThreshold >= 0 &&
1354 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1355 UseCalls = true;
1356
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001357 // Instrument.
1358 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001359 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001360 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1361 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001362 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001363 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001364 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001365 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001366 }
1367 NumInstrumented++;
1368 }
1369
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001370 FunctionStackPoisoner FSP(F, *this);
1371 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001372
1373 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1374 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001375 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001376 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001377 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001378 }
1379
Alexey Samsonova02e6642014-05-29 18:40:48 +00001380 for (auto Inst : PointerComparisonsOrSubtracts) {
1381 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001382 NumInstrumented++;
1383 }
1384
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001385 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001386
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001387 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1388
1389 if (ClKeepUninstrumented) {
1390 if (!res) {
1391 // No instrumentation is done, no need for the duplicate.
1392 if (UninstrumentedDuplicate)
1393 UninstrumentedDuplicate->eraseFromParent();
1394 } else {
1395 // The function was instrumented. We must have the duplicate.
1396 assert(UninstrumentedDuplicate);
1397 UninstrumentedDuplicate->setSection("NOASAN");
1398 assert(!F.hasSection());
1399 F.setSection("ASAN");
1400 }
1401 }
1402
1403 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001404}
1405
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001406// Workaround for bug 11395: we don't want to instrument stack in functions
1407// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1408// FIXME: remove once the bug 11395 is fixed.
1409bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1410 if (LongSize != 32) return false;
1411 CallInst *CI = dyn_cast<CallInst>(I);
1412 if (!CI || !CI->isInlineAsm()) return false;
1413 if (CI->getNumArgOperands() <= 5) return false;
1414 // We have inline assembly with quite a few arguments.
1415 return true;
1416}
1417
1418void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1419 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001420 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1421 std::string Suffix = itostr(i);
1422 AsanStackMallocFunc[i] = checkInterfaceFunction(
1423 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1424 IntptrTy, IntptrTy, NULL));
1425 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1426 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1427 IntptrTy, IntptrTy, NULL));
1428 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001429 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1430 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1431 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1432 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1433}
1434
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001435void
Craig Topper3af97222014-08-27 05:25:00 +00001436FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001437 IRBuilder<> &IRB, Value *ShadowBase,
1438 bool DoPoison) {
1439 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001440 size_t i = 0;
1441 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1442 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1443 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1444 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1445 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1446 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1447 uint64_t Val = 0;
1448 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001449 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001450 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1451 else
1452 Val = (Val << 8) | ShadowBytes[i + j];
1453 }
1454 if (!Val) continue;
1455 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1456 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1457 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1458 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001459 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001460 }
1461}
1462
Kostya Serebryany6805de52013-09-10 13:16:56 +00001463// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1464// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1465static int StackMallocSizeClass(uint64_t LocalStackSize) {
1466 assert(LocalStackSize <= kMaxStackMallocSize);
1467 uint64_t MaxSize = kMinStackMallocSize;
1468 for (int i = 0; ; i++, MaxSize *= 2)
1469 if (LocalStackSize <= MaxSize)
1470 return i;
1471 llvm_unreachable("impossible LocalStackSize");
1472}
1473
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001474// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1475// We can not use MemSet intrinsic because it may end up calling the actual
1476// memset. Size is a multiple of 8.
1477// Currently this generates 8-byte stores on x86_64; it may be better to
1478// generate wider stores.
1479void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1480 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1481 assert(!(Size % 8));
1482 assert(kAsanStackAfterReturnMagic == 0xf5);
1483 for (int i = 0; i < Size; i += 8) {
1484 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1485 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1486 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1487 }
1488}
1489
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001490static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001491 for (const auto &Inst : F.getEntryBlock())
1492 if (!isa<AllocaInst>(Inst))
1493 return Inst.getDebugLoc();
1494 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001495}
1496
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001497void FunctionStackPoisoner::poisonStack() {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001498 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001499 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001500
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001501 assert(AllocaVec.size() > 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001502 Instruction *InsBefore = AllocaVec[0];
1503 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001504 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001505
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001506 SmallVector<ASanStackVariableDescription, 16> SVD;
1507 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001508 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001509 ASanStackVariableDescription D = { AI->getName().data(),
1510 getAllocaSizeInBytes(AI),
1511 AI->getAlignment(), AI, 0};
1512 SVD.push_back(D);
1513 }
1514 // Minimal header size (left redzone) is 4 pointers,
1515 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1516 size_t MinHeaderSize = ASan.LongSize / 2;
1517 ASanStackFrameLayout L;
1518 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1519 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1520 uint64_t LocalStackSize = L.FrameSize;
1521 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001522 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001523
1524 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1525 AllocaInst *MyAlloca =
1526 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001527 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001528 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1529 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1530 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001531 assert(MyAlloca->isStaticAlloca());
1532 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1533 Value *LocalStackBase = OrigStackBase;
1534
1535 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001536 // LocalStackBase = OrigStackBase
1537 // if (__asan_option_detect_stack_use_after_return)
1538 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001539 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1540 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001541 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1542 kAsanOptionDetectUAR, IRB.getInt32Ty());
1543 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1544 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001545 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001546 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1547 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001548 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001549 LocalStackBase = IRBIf.CreateCall2(
1550 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001551 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001552 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1553 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001554 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001555 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1556 Phi->addIncoming(OrigStackBase, CmpBlock);
1557 Phi->addIncoming(LocalStackBase, SetBlock);
1558 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001559 }
1560
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001561 // Insert poison calls for lifetime intrinsics for alloca.
1562 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001563 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001564 assert(APC.InsBefore);
1565 assert(APC.AI);
1566 IRBuilder<> IRB(APC.InsBefore);
1567 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001568 HavePoisonedAllocas |= APC.DoPoison;
1569 }
1570
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001571 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001572 for (const auto &Desc : SVD) {
1573 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001574 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001575 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001576 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001577 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001578 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001579 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001580
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001581 // The left-most redzone has enough space for at least 4 pointers.
1582 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001583 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1584 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1585 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001586 // Write the frame description constant to redzone[1].
1587 Value *BasePlus1 = IRB.CreateIntToPtr(
1588 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1589 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001590 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001591 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1592 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001593 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1594 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001595 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001596 // Write the PC to redzone[2].
1597 Value *BasePlus2 = IRB.CreateIntToPtr(
1598 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1599 2 * ASan.LongSize/8)),
1600 IntptrPtrTy);
1601 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001602
1603 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001604 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001605 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001606
Kostya Serebryany530e2072013-12-23 14:15:08 +00001607 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001608 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001609 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001610 // Mark the current frame as retired.
1611 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1612 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001613 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001614 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001615 // if LocalStackBase != OrigStackBase:
1616 // // In use-after-return mode, poison the whole stack frame.
1617 // if StackMallocIdx <= 4
1618 // // For small sizes inline the whole thing:
1619 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1620 // **SavedFlagPtr(LocalStackBase) = 0
1621 // else
1622 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1623 // else
1624 // <This is not a fake stack; unpoison the redzones>
1625 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1626 TerminatorInst *ThenTerm, *ElseTerm;
1627 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1628
1629 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001630 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001631 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1632 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1633 ClassSize >> Mapping.Scale);
1634 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1635 LocalStackBase,
1636 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1637 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1638 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1639 IRBPoison.CreateStore(
1640 Constant::getNullValue(IRBPoison.getInt8Ty()),
1641 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1642 } else {
1643 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001644 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1645 ConstantInt::get(IntptrTy, LocalStackSize),
1646 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001647 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001648
1649 IRBuilder<> IRBElse(ElseTerm);
1650 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001651 } else if (HavePoisonedAllocas) {
1652 // If we poisoned some allocas in llvm.lifetime analysis,
1653 // unpoison whole stack frame now.
1654 assert(LocalStackBase == OrigStackBase);
1655 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001656 } else {
1657 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001658 }
1659 }
1660
Kostya Serebryany09959942012-10-19 06:20:53 +00001661 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001662 for (auto AI : AllocaVec)
1663 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001664}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001665
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001666void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001667 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001668 // For now just insert the call to ASan runtime.
1669 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1670 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1671 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1672 : AsanUnpoisonStackMemoryFunc,
1673 AddrArg, SizeArg);
1674}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001675
1676// Handling llvm.lifetime intrinsics for a given %alloca:
1677// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1678// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1679// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1680// could be poisoned by previous llvm.lifetime.end instruction, as the
1681// variable may go in and out of scope several times, e.g. in loops).
1682// (3) if we poisoned at least one %alloca in a function,
1683// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001684
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001685AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1686 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1687 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001688 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001689 // See if we've already calculated (or started to calculate) alloca for a
1690 // given value.
1691 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1692 if (I != AllocaForValue.end())
1693 return I->second;
1694 // Store 0 while we're calculating alloca for value V to avoid
1695 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001696 AllocaForValue[V] = nullptr;
1697 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001698 if (CastInst *CI = dyn_cast<CastInst>(V))
1699 Res = findAllocaForValue(CI->getOperand(0));
1700 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1702 Value *IncValue = PN->getIncomingValue(i);
1703 // Allow self-referencing phi-nodes.
1704 if (IncValue == PN) continue;
1705 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1706 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001707 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1708 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001709 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001710 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001711 }
Craig Topperf40110f2014-04-25 05:29:35 +00001712 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001713 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001714 return Res;
1715}