blob: 124ffe2f8f87d7e99cff85ae49050ac5970252bd [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 Serebryany4fb78012013-12-06 09:00:17 +000043#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000045#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000046#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000048#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051
52using namespace llvm;
53
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "asan"
55
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056static const uint64_t kDefaultShadowScale = 3;
57static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000058static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000059static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000060static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000061static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany9e62b302013-06-03 14:46:56 +000062static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000063static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065
Kostya Serebryany6805de52013-09-10 13:16:56 +000066static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const size_t kMaxStackMallocSize = 1 << 16; // 64K
68static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
69static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
70
Craig Topperd3a34f82013-07-16 01:17:10 +000071static const char *const kAsanModuleCtorName = "asan.module_ctor";
72static const char *const kAsanModuleDtorName = "asan.module_dtor";
Alexey Samsonov1f647502014-05-29 01:10:14 +000073static const int kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000074static const char *const kAsanReportErrorTemplate = "__asan_report_";
75static const char *const kAsanReportLoadN = "__asan_report_load_n";
76static const char *const kAsanReportStoreN = "__asan_report_store_n";
77static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000078static const char *const kAsanUnregisterGlobalsName =
79 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000080static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
81static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000082static const char *const kAsanInitName = "__asan_init_v4";
Evgeniy Stepanov47b1a952014-05-27 12:39:31 +000083static const char *const kAsanCovModuleInitName = "__sanitizer_cov_module_init";
Bob Wilsonda4147c2013-11-15 07:16:09 +000084static const char *const kAsanCovName = "__sanitizer_cov";
Kostya Serebryany796f6552014-02-27 12:45:36 +000085static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
86static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000088static const int kMaxAsanStackMallocSizeClass = 10;
89static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
90static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanGenPrefix = "__asan_gen_";
92static const char *const kAsanPoisonStackMemoryName =
93 "__asan_poison_stack_memory";
94static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000095 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000096
Kostya Serebryanyf3223822013-09-18 14:07:14 +000097static const char *const kAsanOptionDetectUAR =
98 "__asan_option_detect_stack_use_after_return";
99
David Blaikieeacc2872013-09-18 00:11:27 +0000100#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000101static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000102#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000103
Kostya Serebryany874dae62012-07-16 16:15:40 +0000104// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
105static const size_t kNumberOfAccessSizes = 5;
106
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000107// Command-line flags.
108
109// This flag may need to be replaced with -f[no-]asan-reads.
110static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
111 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
112static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
113 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000114static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
115 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
116 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000117static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
118 cl::desc("use instrumentation with slow path for all accesses"),
119 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000120// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000121// in any given BB. Normally, this should be set to unlimited (INT_MAX),
122// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
123// set it to 10000.
124static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
125 cl::init(10000),
126 cl::desc("maximal number of instructions to instrument in any given BB"),
127 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000128// This flag may need to be replaced with -f[no]asan-stack.
129static cl::opt<bool> ClStack("asan-stack",
130 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000131static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000132 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000133// This flag may need to be replaced with -f[no]asan-globals.
134static cl::opt<bool> ClGlobals("asan-globals",
135 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000136static cl::opt<int> ClCoverage("asan-coverage",
137 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
138 cl::Hidden, cl::init(false));
Kostya Serebryany22e88102014-04-18 08:02:42 +0000139static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
140 cl::desc("Add coverage instrumentation only to the entry block if there "
141 "are more than this number of blocks."),
142 cl::Hidden, cl::init(1500));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000143static cl::opt<bool> ClInitializers("asan-initialization-order",
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000144 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000145static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
146 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
Kostya Serebryanyec346652014-02-27 12:56:20 +0000147 cl::Hidden, cl::init(false));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000148static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
149 cl::desc("Realign stack to the value of this flag (power of two)"),
150 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000151static cl::opt<int> ClInstrumentationWithCallsThreshold(
152 "asan-instrumentation-with-call-threshold",
153 cl::desc("If the function being instrumented contains more than "
154 "this number of memory accesses, use callbacks instead of "
155 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000156 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000157static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
158 "asan-memory-access-callback-prefix",
159 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
160 cl::init("__asan_"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000161
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000162// This is an experimental feature that will allow to choose between
163// instrumented and non-instrumented code at link-time.
164// If this option is on, just before instrumenting a function we create its
165// clone; if the function is not changed by asan the clone is deleted.
166// If we end up with a clone, we put the instrumented function into a section
167// called "ASAN" and the uninstrumented function into a section called "NOASAN".
168//
169// This is still a prototype, we need to figure out a way to keep two copies of
170// a function so that the linker can easily choose one of them.
171static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
172 cl::desc("Keep uninstrumented copies of functions"),
173 cl::Hidden, cl::init(false));
174
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000175// These flags allow to change the shadow mapping.
176// The shadow mapping looks like
177// Shadow = (Mem >> scale) + (1 << offset_log)
178static cl::opt<int> ClMappingScale("asan-mapping-scale",
179 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000180
181// Optimization flags. Not user visible, used mostly for testing
182// and benchmarking the tool.
183static cl::opt<bool> ClOpt("asan-opt",
184 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
185static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
186 cl::desc("Instrument the same temp just once"), cl::Hidden,
187 cl::init(true));
188static cl::opt<bool> ClOptGlobals("asan-opt-globals",
189 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
190
Alexey Samsonovdf624522012-11-29 18:14:24 +0000191static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
192 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
193 cl::Hidden, cl::init(false));
194
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000195// Debug flags.
196static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
197 cl::init(0));
198static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
199 cl::Hidden, cl::init(0));
200static cl::opt<std::string> ClDebugFunc("asan-debug-func",
201 cl::Hidden, cl::desc("Debug func"));
202static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
203 cl::Hidden, cl::init(-1));
204static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
205 cl::Hidden, cl::init(-1));
206
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000207STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
208STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
209STATISTIC(NumOptimizedAccessesToGlobalArray,
210 "Number of optimized accesses to global arrays");
211STATISTIC(NumOptimizedAccessesToGlobalVar,
212 "Number of optimized accesses to global vars");
213
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000214namespace {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000215/// Frontend-provided metadata for global variables.
216class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000217 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000218 struct Entry {
Alexey Samsonov15c96692014-07-12 00:42:52 +0000219 Entry()
220 : SourceLoc(nullptr), Name(nullptr), IsDynInit(false),
221 IsBlacklisted(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000222 GlobalVariable *SourceLoc;
Alexey Samsonov15c96692014-07-12 00:42:52 +0000223 GlobalVariable *Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000224 bool IsDynInit;
225 bool IsBlacklisted;
226 };
227
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000228 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000229
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000230 void init(Module& M) {
231 assert(!inited_);
232 inited_ = true;
233 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
234 if (!Globals)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000235 return;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000236 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000237 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000238 assert(MDN->getNumOperands() == 5);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000239 Value *V = MDN->getOperand(0);
240 // The optimizer may optimize away a global entirely.
241 if (!V)
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000242 continue;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000243 GlobalVariable *GV = cast<GlobalVariable>(V);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000244 // We can already have an entry for GV if it was merged with another
245 // global.
246 Entry &E = Entries[GV];
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000247 if (Value *Loc = MDN->getOperand(1)) {
248 GlobalVariable *GVLoc = cast<GlobalVariable>(Loc);
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000249 E.SourceLoc = GVLoc;
250 addSourceLocationGlobal(GVLoc);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000251 }
Alexey Samsonov15c96692014-07-12 00:42:52 +0000252 if (Value *Name = MDN->getOperand(2)) {
253 GlobalVariable *GVName = cast<GlobalVariable>(Name);
254 E.Name = GVName;
255 InstrumentationGlobals.insert(GVName);
256 }
257 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000258 E.IsDynInit |= IsDynInit->isOne();
Alexey Samsonov15c96692014-07-12 00:42:52 +0000259 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000260 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000261 }
262 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000263
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000264 /// Returns metadata entry for a given global.
265 Entry get(GlobalVariable *G) const {
266 auto Pos = Entries.find(G);
267 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000268 }
269
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000270 /// Check if the global was generated by the instrumentation
271 /// (we don't want to instrument it again in this case).
272 bool isInstrumentationGlobal(GlobalVariable *G) const {
273 return InstrumentationGlobals.count(G);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000274 }
275
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000276 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000277 bool inited_;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000278 DenseMap<GlobalVariable*, Entry> Entries;
279 // Globals generated by the frontend instrumentation.
280 DenseSet<GlobalVariable*> InstrumentationGlobals;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000281
282 void addSourceLocationGlobal(GlobalVariable *SourceLocGV) {
283 // Source location global is a struct with layout:
284 // {
285 // filename,
286 // i32 line_number,
287 // i32 column_number,
288 // }
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000289 InstrumentationGlobals.insert(SourceLocGV);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000290 ConstantStruct *Contents =
291 cast<ConstantStruct>(SourceLocGV->getInitializer());
292 GlobalVariable *FilenameGV = cast<GlobalVariable>(Contents->getOperand(0));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000293 InstrumentationGlobals.insert(FilenameGV);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000294 }
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000295};
296
Alexey Samsonov1345d352013-01-16 13:23:28 +0000297/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000298/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000299struct ShadowMapping {
300 int Scale;
301 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000302 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000303};
304
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000305static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000306 llvm::Triple TargetTriple(M.getTargetTriple());
307 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000308 bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000309 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000310 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000311 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
312 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000313 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000314 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
315 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000316
317 ShadowMapping Mapping;
318
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000319 if (LongSize == 32) {
320 if (IsAndroid)
321 Mapping.Offset = 0;
322 else if (IsMIPS32)
323 Mapping.Offset = kMIPS32_ShadowOffset32;
324 else if (IsFreeBSD)
325 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000326 else if (IsIOS)
327 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000328 else
329 Mapping.Offset = kDefaultShadowOffset32;
330 } else { // LongSize == 64
331 if (IsPPC64)
332 Mapping.Offset = kPPC64_ShadowOffset64;
333 else if (IsFreeBSD)
334 Mapping.Offset = kFreeBSD_ShadowOffset64;
335 else if (IsLinux && IsX86_64)
336 Mapping.Offset = kSmallX86_64ShadowOffset;
337 else
338 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000339 }
340
341 Mapping.Scale = kDefaultShadowScale;
342 if (ClMappingScale) {
343 Mapping.Scale = ClMappingScale;
344 }
345
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000346 // OR-ing shadow offset if more efficient (at least on x86) if the offset
347 // is a power of two, but on ppc64 we have to use add since the shadow
348 // offset is not necessary 1/8-th of the address space.
349 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
350
Alexey Samsonov1345d352013-01-16 13:23:28 +0000351 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000352}
353
Alexey Samsonov1345d352013-01-16 13:23:28 +0000354static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000355 // Redzone used for stack and globals is at least 32 bytes.
356 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000357 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000358}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000359
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000360/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000361struct AddressSanitizer : public FunctionPass {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000362 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000363 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000364 return "AddressSanitizerFunctionPass";
365 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000366 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000367 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000368 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
369 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000370 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000371 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
372 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000373 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000374 bool IsWrite, size_t AccessSizeIndex,
375 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000376 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000377 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000378 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000379 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000380 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000381 static char ID; // Pass identification, replacement for typeid
382
383 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000384 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000385
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000386 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000387 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000388 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
389 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000390
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000391 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000392 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000393 int LongSize;
394 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000395 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000396 Function *AsanCtorFunction;
397 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000398 Function *AsanHandleNoReturnFunc;
Bob Wilsonda4147c2013-11-15 07:16:09 +0000399 Function *AsanCovFunction;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000400 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000401 // This array is indexed by AccessIsWrite and log2(AccessSize).
402 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000403 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000404 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000405 Function *AsanErrorCallbackSized[2],
406 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000407 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000408 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000409 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000410
411 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000412};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000413
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000414class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000415 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000416 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000417 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000418 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000419 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000420 return "AddressSanitizerModule";
421 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000422
Kostya Serebryany20a79972012-11-22 03:18:50 +0000423 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000424 void initializeCallbacks(Module &M);
425
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000426 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000427 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000428 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000429 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000430 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000431 return RedzoneSizeForScale(Mapping.Scale);
432 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000433
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000434 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000435 Type *IntptrTy;
436 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000437 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000438 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000439 Function *AsanPoisonGlobals;
440 Function *AsanUnpoisonGlobals;
441 Function *AsanRegisterGlobals;
442 Function *AsanUnregisterGlobals;
Evgeniy Stepanov47b1a952014-05-27 12:39:31 +0000443 Function *AsanCovModuleInit;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000444};
445
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000446// Stack poisoning does not play well with exception handling.
447// When an exception is thrown, we essentially bypass the code
448// that unpoisones the stack. This is why the run-time library has
449// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
450// stack in the interceptor. This however does not work inside the
451// actual function which catches the exception. Most likely because the
452// compiler hoists the load of the shadow value somewhere too high.
453// This causes asan to report a non-existing bug on 453.povray.
454// It sounds like an LLVM bug.
455struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
456 Function &F;
457 AddressSanitizer &ASan;
458 DIBuilder DIB;
459 LLVMContext *C;
460 Type *IntptrTy;
461 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000462 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000463
464 SmallVector<AllocaInst*, 16> AllocaVec;
465 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000466 unsigned StackAlignment;
467
Kostya Serebryany6805de52013-09-10 13:16:56 +0000468 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
469 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000470 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
471
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000472 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
473 struct AllocaPoisonCall {
474 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000475 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000476 uint64_t Size;
477 bool DoPoison;
478 };
479 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
480
481 // Maps Value to an AllocaInst from which the Value is originated.
482 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
483 AllocaForValueMapTy AllocaForValue;
484
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000485 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
486 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
487 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000488 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000489 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000490
491 bool runOnFunction() {
492 if (!ClStack) return false;
493 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000494 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000495 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000496
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000497 if (AllocaVec.empty()) return false;
498
499 initializeCallbacks(*F.getParent());
500
501 poisonStack();
502
503 if (ClDebugStack) {
504 DEBUG(dbgs() << F);
505 }
506 return true;
507 }
508
509 // Finds all static Alloca instructions and puts
510 // poisoned red zones around all of them.
511 // Then unpoison everything back before the function returns.
512 void poisonStack();
513
514 // ----------------------- Visitors.
515 /// \brief Collect all Ret instructions.
516 void visitReturnInst(ReturnInst &RI) {
517 RetVec.push_back(&RI);
518 }
519
520 /// \brief Collect Alloca instructions we want (and can) handle.
521 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000522 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000523
524 StackAlignment = std::max(StackAlignment, AI.getAlignment());
525 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000526 }
527
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000528 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
529 /// errors.
530 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000531 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000532 Intrinsic::ID ID = II.getIntrinsicID();
533 if (ID != Intrinsic::lifetime_start &&
534 ID != Intrinsic::lifetime_end)
535 return;
536 // Found lifetime intrinsic, add ASan instrumentation if necessary.
537 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
538 // If size argument is undefined, don't do anything.
539 if (Size->isMinusOne()) return;
540 // Check that size doesn't saturate uint64_t and can
541 // be stored in IntptrTy.
542 const uint64_t SizeValue = Size->getValue().getLimitedValue();
543 if (SizeValue == ~0ULL ||
544 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
545 return;
546 // Find alloca instruction that corresponds to llvm.lifetime argument.
547 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
548 if (!AI) return;
549 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000550 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000551 AllocaPoisonCallVec.push_back(APC);
552 }
553
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000554 // ---------------------- Helpers.
555 void initializeCallbacks(Module &M);
556
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000557 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000558 bool isInterestingAlloca(AllocaInst &AI) const {
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000559 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
560 AI.getAllocatedType()->isSized() &&
561 // alloca() may be called with 0 size, ignore it.
562 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000563 }
564
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000565 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000566 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000567 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000568 return SizeInBytes;
569 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000570 /// Finds alloca where the value comes from.
571 AllocaInst *findAllocaForValue(Value *V);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000572 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000573 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000574 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000575
576 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
577 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000578};
579
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000580} // namespace
581
582char AddressSanitizer::ID = 0;
583INITIALIZE_PASS(AddressSanitizer, "asan",
584 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
585 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000586FunctionPass *llvm::createAddressSanitizerFunctionPass() {
587 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000588}
589
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000590char AddressSanitizerModule::ID = 0;
591INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
592 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
593 "ModulePass", false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000594ModulePass *llvm::createAddressSanitizerModulePass() {
595 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000596}
597
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000598static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000599 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000600 assert(Res < kNumberOfAccessSizes);
601 return Res;
602}
603
Bill Wendling58f8cef2013-08-06 22:52:42 +0000604// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000605static GlobalVariable *createPrivateGlobalForString(
606 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000607 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000608 // We use private linkage for module-local strings. If they can be merged
609 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000610 GlobalVariable *GV =
611 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000612 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
613 if (AllowMerging)
614 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000615 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
616 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000617}
618
619static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
620 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000621}
622
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000623Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
624 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000625 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
626 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000627 return Shadow;
628 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000629 if (Mapping.OrShadowOffset)
630 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
631 else
632 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000633}
634
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000635// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000636void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
637 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000638 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000639 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000640 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
641 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
642 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
643 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
644 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000645 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000646 AsanMemset,
647 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
648 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
649 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000650 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000651 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000652}
653
Kostya Serebryany90241602012-05-30 09:04:06 +0000654// If I is an interesting memory access, return the PointerOperand
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000655// and set IsWrite/Alignment. Otherwise return NULL.
656static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
657 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000658 // Skip memory accesses inserted by another instrumentation.
659 if (I->getMetadata("nosanitize"))
660 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000661 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000662 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000663 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000664 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000665 return LI->getPointerOperand();
666 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000667 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000668 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000669 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000670 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000671 return SI->getPointerOperand();
672 }
673 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000674 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000675 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000676 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000677 return RMW->getPointerOperand();
678 }
679 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000680 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000681 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000682 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000683 return XCHG->getPointerOperand();
684 }
Craig Topperf40110f2014-04-25 05:29:35 +0000685 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000686}
687
Kostya Serebryany796f6552014-02-27 12:45:36 +0000688static bool isPointerOperand(Value *V) {
689 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
690}
691
692// This is a rough heuristic; it may cause both false positives and
693// false negatives. The proper implementation requires cooperation with
694// the frontend.
695static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
696 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
697 if (!Cmp->isRelational())
698 return false;
699 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000700 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000701 return false;
702 } else {
703 return false;
704 }
705 if (!isPointerOperand(I->getOperand(0)) ||
706 !isPointerOperand(I->getOperand(1)))
707 return false;
708 return true;
709}
710
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000711bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
712 // If a global variable does not have dynamic initialization we don't
713 // have to instrument it. However, if a global does not have initializer
714 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000715 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000716}
717
Kostya Serebryany796f6552014-02-27 12:45:36 +0000718void
719AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
720 IRBuilder<> IRB(I);
721 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
722 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
723 for (int i = 0; i < 2; i++) {
724 if (Param[i]->getType()->isPointerTy())
725 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
726 }
727 IRB.CreateCall2(F, Param[0], Param[1]);
728}
729
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000730void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000731 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000732 unsigned Alignment = 0;
733 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000734 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000735 if (ClOpt && ClOptGlobals) {
736 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
737 // If initialization order checking is disabled, a simple access to a
738 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000739 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000740 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000741 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000742 }
743 }
744 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
745 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
746 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
747 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
748 NumOptimizedAccessesToGlobalArray++;
749 return;
750 }
751 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000752 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000753 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000754
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000755 Type *OrigPtrTy = Addr->getType();
756 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
757
758 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000759 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000760
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000761 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000762
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000763 if (IsWrite)
764 NumInstrumentedWrites++;
765 else
766 NumInstrumentedReads++;
767
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000768 unsigned Granularity = 1 << Mapping.Scale;
769 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
770 // if the data is properly aligned.
771 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
772 TypeSize == 128) &&
773 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000774 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000775 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000776 // We can not do it with a single check, so we do 1-byte check for the first
777 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
778 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000779 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000780 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000781 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
782 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000783 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000784 } else {
785 Value *LastByte = IRB.CreateIntToPtr(
786 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
787 OrigPtrTy);
788 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
789 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
790 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000791}
792
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000793// Validate the result of Module::getOrInsertFunction called for an interface
794// function of AddressSanitizer. If the instrumented module defines a function
795// with the same name, their prototypes must match, otherwise
796// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000797static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000798 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
799 FuncOrBitcast->dump();
800 report_fatal_error("trying to redefine an AddressSanitizer "
801 "interface function");
802}
803
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000804Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000805 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000806 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000807 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000808 CallInst *Call = SizeArgument
809 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
810 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
811
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000812 // We don't do Call->setDoesNotReturn() because the BB already has
813 // UnreachableInst at the end.
814 // This EmptyAsm is required to avoid callback merge.
815 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000816 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000817}
818
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000819Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000820 Value *ShadowValue,
821 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000822 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000823 // Addr & (Granularity - 1)
824 Value *LastAccessedByte = IRB.CreateAnd(
825 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
826 // (Addr & (Granularity - 1)) + size - 1
827 if (TypeSize / 8 > 1)
828 LastAccessedByte = IRB.CreateAdd(
829 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
830 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
831 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000832 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000833 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
834 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
835}
836
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000837void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000838 Instruction *InsertBefore, Value *Addr,
839 uint32_t TypeSize, bool IsWrite,
840 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000841 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000842 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000843 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
844
845 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000846 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
847 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000848 return;
849 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000850
851 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000852 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000853 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
854 Value *ShadowPtr = memToShadow(AddrLong, IRB);
855 Value *CmpVal = Constant::getNullValue(ShadowTy);
856 Value *ShadowValue = IRB.CreateLoad(
857 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
858
859 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000860 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000861 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000862
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000863 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000864 TerminatorInst *CheckTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000865 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
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.
910 // (CS->getOperand(0) is the init priority.)
911 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
912 if (F->getName() != kAsanModuleCtorName)
913 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000914 }
915 }
916}
917
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000918bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000919 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +0000920 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000921
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000922 if (GlobalsMD.get(G).IsBlacklisted) return false;
923 if (GlobalsMD.isInstrumentationGlobal(G)) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000924 if (!Ty->isSized()) return false;
925 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000926 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000927 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000928 // Don't handle ODR linkage types and COMDATs since other modules may be built
929 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000930 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
931 G->getLinkage() != GlobalVariable::PrivateLinkage &&
932 G->getLinkage() != GlobalVariable::InternalLinkage)
933 return false;
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +0000934 if (G->hasComdat())
935 return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000936 // Two problems with thread-locals:
937 // - The address of the main thread's copy can't be computed at link-time.
938 // - Need to poison all copies, not just the main thread's one.
939 if (G->isThreadLocal())
940 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000941 // For now, just ignore this Global if the alignment is large.
942 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000943
944 // Ignore all the globals with the names starting with "\01L_OBJC_".
945 // Many of those are put into the .cstring section. The linker compresses
946 // that section by removing the spare \0s after the string terminator, so
947 // our redzones get broken.
948 if ((G->getName().find("\01L_OBJC_") == 0) ||
949 (G->getName().find("\01l_OBJC_") == 0)) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000950 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000951 return false;
952 }
953
954 if (G->hasSection()) {
955 StringRef Section(G->getSection());
956 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
957 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
958 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000959 if (Section.startswith("__OBJC,") ||
960 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000961 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000962 return false;
963 }
964 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
965 // Constant CFString instances are compiled in the following way:
966 // -- the string buffer is emitted into
967 // __TEXT,__cstring,cstring_literals
968 // -- the constant NSConstantString structure referencing that buffer
969 // is placed into __DATA,__cfstring
970 // Therefore there's no point in placing redzones into __DATA,__cfstring.
971 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000972 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000973 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
974 return false;
975 }
976 // The linker merges the contents of cstring_literals and removes the
977 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000978 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000979 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000980 return false;
981 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000982
983 // Callbacks put into the CRT initializer/terminator sections
984 // should not be instrumented.
985 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
986 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
987 if (Section.startswith(".CRT")) {
988 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
989 return false;
990 }
991
Alexander Potapenko04969e82014-03-20 10:48:34 +0000992 // Globals from llvm.metadata aren't emitted, do not instrument them.
993 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000994 }
995
996 return true;
997}
998
Alexey Samsonov788381b2012-12-25 12:28:20 +0000999void AddressSanitizerModule::initializeCallbacks(Module &M) {
1000 IRBuilder<> IRB(*C);
1001 // Declare our poisoning and unpoisoning functions.
1002 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001003 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001004 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1005 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1006 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1007 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1008 // Declare functions that register/unregister globals.
1009 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1010 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1011 IntptrTy, IntptrTy, NULL));
1012 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1013 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1014 kAsanUnregisterGlobalsName,
1015 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1016 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov47b1a952014-05-27 12:39:31 +00001017 AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
1018 kAsanCovModuleInitName,
1019 IRB.getVoidTy(), IntptrTy, NULL));
1020 AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001021}
1022
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001023// This function replaces all global variables with new variables that have
1024// trailing redzones. It also creates a function that poisons
1025// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001026bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001027 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001028
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001029 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1030
Alexey Samsonova02e6642014-05-29 18:40:48 +00001031 for (auto &G : M.globals()) {
1032 if (ShouldInstrumentGlobal(&G))
1033 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001034 }
1035
1036 size_t n = GlobalsToChange.size();
1037 if (n == 0) return false;
1038
1039 // A global is described by a structure
1040 // size_t beg;
1041 // size_t size;
1042 // size_t size_with_redzone;
1043 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001044 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001045 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001046 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001047 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001048 StructType *GlobalStructTy =
1049 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1050 IntptrTy, IntptrTy, NULL);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001051 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001052
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001053 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001054
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001055 // We shouldn't merge same module names, as this string serves as unique
1056 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001057 GlobalVariable *ModuleName = createPrivateGlobalForString(
1058 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001059
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001060 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001061 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001062 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001063
1064 auto MD = GlobalsMD.get(G);
1065 // Create string holding the global name unless it was provided by
1066 // the metadata.
1067 GlobalVariable *Name =
1068 MD.Name ? MD.Name : createPrivateGlobalForString(M, G->getName(),
1069 /*AllowMerging*/ true);
1070
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001071 PointerType *PtrTy = cast<PointerType>(G->getType());
1072 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001073 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001074 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001075 // MinRZ <= RZ <= kMaxGlobalRedzone
1076 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001077 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001078 std::min(kMaxGlobalRedzone,
1079 (SizeInBytes / MinRZ / 4) * MinRZ));
1080 uint64_t RightRedzoneSize = RZ;
1081 // Round up to MinRZ
1082 if (SizeInBytes % MinRZ)
1083 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1084 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001085 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1086
1087 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1088 Constant *NewInitializer = ConstantStruct::get(
1089 NewTy, G->getInitializer(),
1090 Constant::getNullValue(RightRedZoneTy), NULL);
1091
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001092 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001093 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1094 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1095 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001096 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001097 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001098 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001099 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001100 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001101
1102 Value *Indices2[2];
1103 Indices2[0] = IRB.getInt32(0);
1104 Indices2[1] = IRB.getInt32(0);
1105
1106 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001107 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001108 NewGlobal->takeName(G);
1109 G->eraseFromParent();
1110
1111 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 Samsonov08f022a2014-07-11 22:36:02 +00001117 ConstantInt::get(IntptrTy, MD.IsDynInit),
1118 MD.SourceLoc ? ConstantExpr::getPointerCast(MD.SourceLoc, IntptrTy)
1119 : ConstantInt::get(IntptrTy, 0),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001120 NULL);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001121
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001122 if (ClInitializers && MD.IsDynInit)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001123 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001124
Kostya Serebryany20343352012-10-17 13:40:06 +00001125 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001126 }
1127
1128 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1129 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001130 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001131 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1132
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001133 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001134 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001135 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001136 IRB.CreateCall2(AsanRegisterGlobals,
1137 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1138 ConstantInt::get(IntptrTy, n));
1139
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001140 // We also need to unregister globals at the end, e.g. when a shared library
1141 // gets closed.
1142 Function *AsanDtorFunction = Function::Create(
1143 FunctionType::get(Type::getVoidTy(*C), false),
1144 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1145 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1146 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001147 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1148 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1149 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001150 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001151
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001152 DEBUG(dbgs() << M);
1153 return true;
1154}
1155
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001156bool AddressSanitizerModule::runOnModule(Module &M) {
1157 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1158 if (!DLP)
1159 return false;
1160 DL = &DLP->getDataLayout();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001161 C = &(M.getContext());
1162 int LongSize = DL->getPointerSizeInBits();
1163 IntptrTy = Type::getIntNTy(*C, LongSize);
1164 Mapping = getShadowMapping(M, LongSize);
1165 initializeCallbacks(M);
1166
1167 bool Changed = false;
1168
1169 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1170 assert(CtorFunc);
1171 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1172
1173 if (ClCoverage > 0) {
1174 Function *CovFunc = M.getFunction(kAsanCovName);
1175 int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1176 IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1177 Changed = true;
1178 }
1179
Alexey Samsonovc94285a2014-07-08 00:50:49 +00001180 if (ClGlobals)
1181 Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001182
1183 return Changed;
1184}
1185
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001186void AddressSanitizer::initializeCallbacks(Module &M) {
1187 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001188 // Create __asan_report* callbacks.
1189 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1190 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1191 AccessSizeIndex++) {
1192 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001193 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001194 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001195 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001196 checkInterfaceFunction(
1197 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1198 IRB.getVoidTy(), IntptrTy, NULL));
1199 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1200 checkInterfaceFunction(
1201 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1202 IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001203 }
1204 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001205 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1206 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1207 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1208 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001209
Kostya Serebryany86332c02014-04-21 07:10:43 +00001210 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1211 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1212 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1213 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1214 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1215 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1216
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001217 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1218 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1219 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1220 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1221 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1222 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1223 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1224 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1225 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1226
1227 AsanHandleNoReturnFunc = checkInterfaceFunction(
1228 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Bob Wilsonda4147c2013-11-15 07:16:09 +00001229 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001230 kAsanCovName, IRB.getVoidTy(), NULL));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001231 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1232 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1233 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1234 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001235 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1236 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1237 StringRef(""), StringRef(""),
1238 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001239}
1240
1241// virtual
1242bool AddressSanitizer::doInitialization(Module &M) {
1243 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001244 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1245 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001246 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001247 DL = &DLP->getDataLayout();
1248
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001249 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001250
1251 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001252 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001253 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001254
1255 AsanCtorFunction = Function::Create(
1256 FunctionType::get(Type::getVoidTy(*C), false),
1257 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1258 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1259 // call __asan_init in the module ctor.
1260 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1261 AsanInitFunction = checkInterfaceFunction(
1262 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1263 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1264 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001265
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001266 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001267
Alexey Samsonov1f647502014-05-29 01:10:14 +00001268 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001269 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001270}
1271
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001272bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1273 // For each NSObject descendant having a +load method, this method is invoked
1274 // by the ObjC runtime before any of the static constructors is called.
1275 // Therefore we need to instrument such methods with a call to __asan_init
1276 // at the beginning in order to initialize our runtime before any access to
1277 // the shadow memory.
1278 // We cannot just ignore these methods, because they may call other
1279 // instrumented functions.
1280 if (F.getName().find(" load]") != std::string::npos) {
1281 IRBuilder<> IRB(F.begin()->begin());
1282 IRB.CreateCall(AsanInitFunction);
1283 return true;
1284 }
1285 return false;
1286}
1287
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001288void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1289 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001290 // Skip static allocas at the top of the entry block so they don't become
1291 // dynamic when we split the block. If we used our optimized stack layout,
1292 // then there will only be one alloca and it will come first.
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001293 for (; IP != BE; ++IP) {
1294 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1295 if (!AI || !AI->isStaticAlloca())
1296 break;
1297 }
1298
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001299 DebugLoc EntryLoc = IP->getDebugLoc().getFnDebugLoc(*C);
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001300 IRBuilder<> IRB(IP);
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001301 IRB.SetCurrentDebugLocation(EntryLoc);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001302 Type *Int8Ty = IRB.getInt8Ty();
1303 GlobalVariable *Guard = new GlobalVariable(
Kostya Serebryany0604c622013-11-15 09:52:05 +00001304 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Bob Wilsonda4147c2013-11-15 07:16:09 +00001305 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1306 LoadInst *Load = IRB.CreateLoad(Guard);
1307 Load->setAtomic(Monotonic);
1308 Load->setAlignment(1);
1309 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001310 Instruction *Ins = SplitBlockAndInsertIfThen(
1311 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Bob Wilsonda4147c2013-11-15 07:16:09 +00001312 IRB.SetInsertPoint(Ins);
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001313 IRB.SetCurrentDebugLocation(EntryLoc);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001314 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1315 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001316 IRB.CreateCall(AsanCovFunction);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001317 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1318 Store->setAtomic(Monotonic);
1319 Store->setAlignment(1);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001320}
1321
1322// Poor man's coverage that works with ASan.
1323// We create a Guard boolean variable with the same linkage
1324// as the function and inject this code into the entry block (-asan-coverage=1)
1325// or all blocks (-asan-coverage=2):
1326// if (*Guard) {
1327// __sanitizer_cov(&F);
1328// *Guard = 1;
1329// }
1330// The accesses to Guard are atomic. The rest of the logic is
1331// in __sanitizer_cov (it's fine to call it more than once).
1332//
1333// This coverage implementation provides very limited data:
1334// it only tells if a given function (block) was ever executed.
1335// No counters, no per-edge data.
1336// But for many use cases this is what we need and the added slowdown
1337// is negligible. This simple implementation will probably be obsoleted
1338// by the upcoming Clang-based coverage implementation.
1339// By having it here and now we hope to
1340// a) get the functionality to users earlier and
1341// b) collect usage statistics to help improve Clang coverage design.
1342bool AddressSanitizer::InjectCoverage(Function &F,
1343 const ArrayRef<BasicBlock *> AllBlocks) {
1344 if (!ClCoverage) return false;
1345
Kostya Serebryany22e88102014-04-18 08:02:42 +00001346 if (ClCoverage == 1 ||
1347 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001348 InjectCoverageAtBlock(F, F.getEntryBlock());
1349 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001350 for (auto BB : AllBlocks)
1351 InjectCoverageAtBlock(F, *BB);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001352 }
Bob Wilsonda4147c2013-11-15 07:16:09 +00001353 return true;
1354}
1355
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001356bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001357 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001358 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001359 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001360 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001361
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001362 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001363 maybeInsertAsanInitAtFunctionEntry(F);
1364
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001365 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001366 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001367
1368 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1369 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001370
1371 // We want to instrument every address only once per basic block (unless there
1372 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001373 SmallSet<Value*, 16> TempsToInstrument;
1374 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001375 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001376 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001377 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001378 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001379 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001380 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001381
1382 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001383 for (auto &BB : F) {
1384 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001385 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001386 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001387 for (auto &Inst : BB) {
1388 if (LooksLikeCodeInBug11395(&Inst)) return false;
1389 if (Value *Addr =
1390 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001391 if (ClOpt && ClOptSameTemp) {
1392 if (!TempsToInstrument.insert(Addr))
1393 continue; // We've seen this temp in the current BB.
1394 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001395 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001396 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1397 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001398 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001399 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001400 // ok, take it.
1401 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001402 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001403 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001404 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001405 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001406 // A call inside BB.
1407 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001408 if (CS.doesNotReturn())
1409 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001410 }
1411 continue;
1412 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001413 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001414 NumInsnsPerBB++;
1415 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1416 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001417 }
1418 }
1419
Craig Topperf40110f2014-04-25 05:29:35 +00001420 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001421 bool LikelyToInstrument =
1422 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1423 if (ClKeepUninstrumented && LikelyToInstrument) {
1424 ValueToValueMapTy VMap;
1425 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1426 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1427 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1428 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1429 }
1430
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001431 bool UseCalls = false;
1432 if (ClInstrumentationWithCallsThreshold >= 0 &&
1433 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1434 UseCalls = true;
1435
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001436 // Instrument.
1437 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001438 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001439 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1440 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001441 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001442 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001443 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001444 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001445 }
1446 NumInstrumented++;
1447 }
1448
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001449 FunctionStackPoisoner FSP(F, *this);
1450 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001451
1452 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1453 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001454 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001455 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001456 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001457 }
1458
Alexey Samsonova02e6642014-05-29 18:40:48 +00001459 for (auto Inst : PointerComparisonsOrSubtracts) {
1460 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001461 NumInstrumented++;
1462 }
1463
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001464 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001465
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001466 if (InjectCoverage(F, AllBlocks))
Bob Wilsonda4147c2013-11-15 07:16:09 +00001467 res = true;
1468
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001469 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1470
1471 if (ClKeepUninstrumented) {
1472 if (!res) {
1473 // No instrumentation is done, no need for the duplicate.
1474 if (UninstrumentedDuplicate)
1475 UninstrumentedDuplicate->eraseFromParent();
1476 } else {
1477 // The function was instrumented. We must have the duplicate.
1478 assert(UninstrumentedDuplicate);
1479 UninstrumentedDuplicate->setSection("NOASAN");
1480 assert(!F.hasSection());
1481 F.setSection("ASAN");
1482 }
1483 }
1484
1485 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001486}
1487
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001488// Workaround for bug 11395: we don't want to instrument stack in functions
1489// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1490// FIXME: remove once the bug 11395 is fixed.
1491bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1492 if (LongSize != 32) return false;
1493 CallInst *CI = dyn_cast<CallInst>(I);
1494 if (!CI || !CI->isInlineAsm()) return false;
1495 if (CI->getNumArgOperands() <= 5) return false;
1496 // We have inline assembly with quite a few arguments.
1497 return true;
1498}
1499
1500void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1501 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001502 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1503 std::string Suffix = itostr(i);
1504 AsanStackMallocFunc[i] = checkInterfaceFunction(
1505 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1506 IntptrTy, IntptrTy, NULL));
1507 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1508 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1509 IntptrTy, IntptrTy, NULL));
1510 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001511 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1512 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1513 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1514 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1515}
1516
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001517void
1518FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1519 IRBuilder<> &IRB, Value *ShadowBase,
1520 bool DoPoison) {
1521 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001522 size_t i = 0;
1523 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1524 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1525 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1526 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1527 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1528 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1529 uint64_t Val = 0;
1530 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001531 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001532 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1533 else
1534 Val = (Val << 8) | ShadowBytes[i + j];
1535 }
1536 if (!Val) continue;
1537 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1538 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1539 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1540 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001541 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001542 }
1543}
1544
Kostya Serebryany6805de52013-09-10 13:16:56 +00001545// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1546// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1547static int StackMallocSizeClass(uint64_t LocalStackSize) {
1548 assert(LocalStackSize <= kMaxStackMallocSize);
1549 uint64_t MaxSize = kMinStackMallocSize;
1550 for (int i = 0; ; i++, MaxSize *= 2)
1551 if (LocalStackSize <= MaxSize)
1552 return i;
1553 llvm_unreachable("impossible LocalStackSize");
1554}
1555
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001556// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1557// We can not use MemSet intrinsic because it may end up calling the actual
1558// memset. Size is a multiple of 8.
1559// Currently this generates 8-byte stores on x86_64; it may be better to
1560// generate wider stores.
1561void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1562 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1563 assert(!(Size % 8));
1564 assert(kAsanStackAfterReturnMagic == 0xf5);
1565 for (int i = 0; i < Size; i += 8) {
1566 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1567 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1568 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1569 }
1570}
1571
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001572static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001573 for (const auto &Inst : F.getEntryBlock())
1574 if (!isa<AllocaInst>(Inst))
1575 return Inst.getDebugLoc();
1576 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001577}
1578
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001579void FunctionStackPoisoner::poisonStack() {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001580 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001581 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001582
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001583 assert(AllocaVec.size() > 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001584 Instruction *InsBefore = AllocaVec[0];
1585 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001586 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001587
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001588 SmallVector<ASanStackVariableDescription, 16> SVD;
1589 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001590 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001591 ASanStackVariableDescription D = { AI->getName().data(),
1592 getAllocaSizeInBytes(AI),
1593 AI->getAlignment(), AI, 0};
1594 SVD.push_back(D);
1595 }
1596 // Minimal header size (left redzone) is 4 pointers,
1597 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1598 size_t MinHeaderSize = ASan.LongSize / 2;
1599 ASanStackFrameLayout L;
1600 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1601 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1602 uint64_t LocalStackSize = L.FrameSize;
1603 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001604 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001605
1606 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1607 AllocaInst *MyAlloca =
1608 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001609 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001610 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1611 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1612 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001613 assert(MyAlloca->isStaticAlloca());
1614 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1615 Value *LocalStackBase = OrigStackBase;
1616
1617 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001618 // LocalStackBase = OrigStackBase
1619 // if (__asan_option_detect_stack_use_after_return)
1620 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001621 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1622 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001623 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1624 kAsanOptionDetectUAR, IRB.getInt32Ty());
1625 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1626 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001627 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001628 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1629 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001630 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001631 LocalStackBase = IRBIf.CreateCall2(
1632 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001633 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001634 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1635 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001636 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001637 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1638 Phi->addIncoming(OrigStackBase, CmpBlock);
1639 Phi->addIncoming(LocalStackBase, SetBlock);
1640 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001641 }
1642
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001643 // Insert poison calls for lifetime intrinsics for alloca.
1644 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001645 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001646 assert(APC.InsBefore);
1647 assert(APC.AI);
1648 IRBuilder<> IRB(APC.InsBefore);
1649 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001650 HavePoisonedAllocas |= APC.DoPoison;
1651 }
1652
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001653 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001654 for (const auto &Desc : SVD) {
1655 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001656 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001657 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001658 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001659 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001660 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001661 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001662
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001663 // The left-most redzone has enough space for at least 4 pointers.
1664 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001665 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1666 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1667 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001668 // Write the frame description constant to redzone[1].
1669 Value *BasePlus1 = IRB.CreateIntToPtr(
1670 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1671 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001672 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001673 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1674 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001675 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1676 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001677 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001678 // Write the PC to redzone[2].
1679 Value *BasePlus2 = IRB.CreateIntToPtr(
1680 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1681 2 * ASan.LongSize/8)),
1682 IntptrPtrTy);
1683 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001684
1685 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001686 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001687 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001688
Kostya Serebryany530e2072013-12-23 14:15:08 +00001689 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001690 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001691 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001692 // Mark the current frame as retired.
1693 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1694 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001695 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001696 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001697 // if LocalStackBase != OrigStackBase:
1698 // // In use-after-return mode, poison the whole stack frame.
1699 // if StackMallocIdx <= 4
1700 // // For small sizes inline the whole thing:
1701 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1702 // **SavedFlagPtr(LocalStackBase) = 0
1703 // else
1704 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1705 // else
1706 // <This is not a fake stack; unpoison the redzones>
1707 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1708 TerminatorInst *ThenTerm, *ElseTerm;
1709 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1710
1711 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001712 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001713 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1714 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1715 ClassSize >> Mapping.Scale);
1716 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1717 LocalStackBase,
1718 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1719 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1720 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1721 IRBPoison.CreateStore(
1722 Constant::getNullValue(IRBPoison.getInt8Ty()),
1723 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1724 } else {
1725 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001726 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1727 ConstantInt::get(IntptrTy, LocalStackSize),
1728 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001729 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001730
1731 IRBuilder<> IRBElse(ElseTerm);
1732 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001733 } else if (HavePoisonedAllocas) {
1734 // If we poisoned some allocas in llvm.lifetime analysis,
1735 // unpoison whole stack frame now.
1736 assert(LocalStackBase == OrigStackBase);
1737 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001738 } else {
1739 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001740 }
1741 }
1742
Kostya Serebryany09959942012-10-19 06:20:53 +00001743 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001744 for (auto AI : AllocaVec)
1745 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001746}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001747
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001748void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001749 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001750 // For now just insert the call to ASan runtime.
1751 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1752 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1753 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1754 : AsanUnpoisonStackMemoryFunc,
1755 AddrArg, SizeArg);
1756}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001757
1758// Handling llvm.lifetime intrinsics for a given %alloca:
1759// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1760// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1761// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1762// could be poisoned by previous llvm.lifetime.end instruction, as the
1763// variable may go in and out of scope several times, e.g. in loops).
1764// (3) if we poisoned at least one %alloca in a function,
1765// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001766
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001767AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1768 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1769 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001770 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001771 // See if we've already calculated (or started to calculate) alloca for a
1772 // given value.
1773 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1774 if (I != AllocaForValue.end())
1775 return I->second;
1776 // Store 0 while we're calculating alloca for value V to avoid
1777 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001778 AllocaForValue[V] = nullptr;
1779 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001780 if (CastInst *CI = dyn_cast<CastInst>(V))
1781 Res = findAllocaForValue(CI->getOperand(0));
1782 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1783 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1784 Value *IncValue = PN->getIncomingValue(i);
1785 // Allow self-referencing phi-nodes.
1786 if (IncValue == PN) continue;
1787 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1788 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001789 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1790 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001791 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001792 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001793 }
Craig Topperf40110f2014-04-25 05:29:35 +00001794 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001795 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001796 return Res;
1797}