blob: 6dbcde03cf2db1e040347e062ef9044d9de3e0a1 [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 Samsonov1e3f7ba2012-12-25 12:04:36 +000019#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000023#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000024#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000025#include "llvm/ADT/Triple.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000026#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000027#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000032#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000035#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/DataTypes.h"
40#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000041#include "llvm/Support/Endian.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000042#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000044#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000045#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000046#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne015370e2013-07-09 22:02:49 +000047#include "llvm/Transforms/Utils/SpecialCaseList.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";
82static const char *const kAsanInitName = "__asan_init_v3";
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));
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000151static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
152 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000153 "during instrumentation"), cl::Hidden);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000154static cl::opt<int> ClInstrumentationWithCallsThreshold(
155 "asan-instrumentation-with-call-threshold",
156 cl::desc("If the function being instrumented contains more than "
157 "this number of memory accesses, use callbacks instead of "
158 "inline checks (-1 means never use callbacks)."),
Kostya Serebryany4d237a82014-05-26 11:57:16 +0000159 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000160static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
161 "asan-memory-access-callback-prefix",
162 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
163 cl::init("__asan_"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000164
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000165// This is an experimental feature that will allow to choose between
166// instrumented and non-instrumented code at link-time.
167// If this option is on, just before instrumenting a function we create its
168// clone; if the function is not changed by asan the clone is deleted.
169// If we end up with a clone, we put the instrumented function into a section
170// called "ASAN" and the uninstrumented function into a section called "NOASAN".
171//
172// This is still a prototype, we need to figure out a way to keep two copies of
173// a function so that the linker can easily choose one of them.
174static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
175 cl::desc("Keep uninstrumented copies of functions"),
176 cl::Hidden, cl::init(false));
177
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000178// These flags allow to change the shadow mapping.
179// The shadow mapping looks like
180// Shadow = (Mem >> scale) + (1 << offset_log)
181static cl::opt<int> ClMappingScale("asan-mapping-scale",
182 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000183
184// Optimization flags. Not user visible, used mostly for testing
185// and benchmarking the tool.
186static cl::opt<bool> ClOpt("asan-opt",
187 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
188static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
189 cl::desc("Instrument the same temp just once"), cl::Hidden,
190 cl::init(true));
191static cl::opt<bool> ClOptGlobals("asan-opt-globals",
192 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
193
Alexey Samsonovdf624522012-11-29 18:14:24 +0000194static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
195 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
196 cl::Hidden, cl::init(false));
197
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000198// Debug flags.
199static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
200 cl::init(0));
201static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
202 cl::Hidden, cl::init(0));
203static cl::opt<std::string> ClDebugFunc("asan-debug-func",
204 cl::Hidden, cl::desc("Debug func"));
205static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
206 cl::Hidden, cl::init(-1));
207static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
208 cl::Hidden, cl::init(-1));
209
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000210STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
211STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
212STATISTIC(NumOptimizedAccessesToGlobalArray,
213 "Number of optimized accesses to global arrays");
214STATISTIC(NumOptimizedAccessesToGlobalVar,
215 "Number of optimized accesses to global vars");
216
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000217namespace {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000218/// A set of dynamically initialized globals extracted from metadata.
219class SetOfDynamicallyInitializedGlobals {
220 public:
221 void Init(Module& M) {
222 // Clang generates metadata identifying all dynamically initialized globals.
223 NamedMDNode *DynamicGlobals =
224 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
225 if (!DynamicGlobals)
226 return;
Alexey Samsonova02e6642014-05-29 18:40:48 +0000227 for (const auto MDN : DynamicGlobals->operands()) {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000228 assert(MDN->getNumOperands() == 1);
229 Value *VG = MDN->getOperand(0);
230 // The optimizer may optimize away a global entirely, in which case we
231 // cannot instrument access to it.
232 if (!VG)
233 continue;
234 DynInitGlobals.insert(cast<GlobalVariable>(VG));
235 }
236 }
237 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
238 private:
239 SmallSet<GlobalValue*, 32> DynInitGlobals;
240};
241
Alexey Samsonov1345d352013-01-16 13:23:28 +0000242/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000243/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000244struct ShadowMapping {
245 int Scale;
246 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000247 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000248};
249
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000250static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000251 llvm::Triple TargetTriple(M.getTargetTriple());
252 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000253 bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000254 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000255 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000256 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
257 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000258 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000259 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
260 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000261
262 ShadowMapping Mapping;
263
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000264 if (LongSize == 32) {
265 if (IsAndroid)
266 Mapping.Offset = 0;
267 else if (IsMIPS32)
268 Mapping.Offset = kMIPS32_ShadowOffset32;
269 else if (IsFreeBSD)
270 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000271 else if (IsIOS)
272 Mapping.Offset = kIOSShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000273 else
274 Mapping.Offset = kDefaultShadowOffset32;
275 } else { // LongSize == 64
276 if (IsPPC64)
277 Mapping.Offset = kPPC64_ShadowOffset64;
278 else if (IsFreeBSD)
279 Mapping.Offset = kFreeBSD_ShadowOffset64;
280 else if (IsLinux && IsX86_64)
281 Mapping.Offset = kSmallX86_64ShadowOffset;
282 else
283 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000284 }
285
286 Mapping.Scale = kDefaultShadowScale;
287 if (ClMappingScale) {
288 Mapping.Scale = ClMappingScale;
289 }
290
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000291 // OR-ing shadow offset if more efficient (at least on x86) if the offset
292 // is a power of two, but on ppc64 we have to use add since the shadow
293 // offset is not necessary 1/8-th of the address space.
294 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
295
Alexey Samsonov1345d352013-01-16 13:23:28 +0000296 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000297}
298
Alexey Samsonov1345d352013-01-16 13:23:28 +0000299static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000300 // Redzone used for stack and globals is at least 32 bytes.
301 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000302 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000303}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000304
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000305/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000306struct AddressSanitizer : public FunctionPass {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000307 AddressSanitizer() : FunctionPass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000308 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000309 return "AddressSanitizerFunctionPass";
310 }
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000311 void instrumentMop(Instruction *I, bool UseCalls);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000312 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000313 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
314 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000315 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000316 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
317 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000318 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000319 bool IsWrite, size_t AccessSizeIndex,
320 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000321 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000322 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000323 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000324 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000325 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000326 static char ID; // Pass identification, replacement for typeid
327
328 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000329 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000330
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000331 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000332 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000333 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
334 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000335
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000336 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000337 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000338 int LongSize;
339 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000340 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000341 Function *AsanCtorFunction;
342 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000343 Function *AsanHandleNoReturnFunc;
Bob Wilsonda4147c2013-11-15 07:16:09 +0000344 Function *AsanCovFunction;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000345 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000346 // This array is indexed by AccessIsWrite and log2(AccessSize).
347 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000348 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000349 // This array is indexed by AccessIsWrite.
Kostya Serebryany86332c02014-04-21 07:10:43 +0000350 Function *AsanErrorCallbackSized[2],
351 *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000352 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000353 InlineAsm *EmptyAsm;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000354 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000355
356 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000357};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000358
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000359class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000360 public:
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000361 AddressSanitizerModule(StringRef BlacklistFile = StringRef())
362 : ModulePass(ID), BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
363 : BlacklistFile) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000364 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000365 static char ID; // Pass identification, replacement for typeid
Craig Topper3e4c6972014-03-05 09:10:37 +0000366 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000367 return "AddressSanitizerModule";
368 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000369
Kostya Serebryany20a79972012-11-22 03:18:50 +0000370 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000371 void initializeCallbacks(Module &M);
372
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000373 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000374 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000375 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000376 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000377 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000378 return RedzoneSizeForScale(Mapping.Scale);
379 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000380
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000381 SmallString<64> BlacklistFile;
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000382
Ahmed Charles56440fd2014-03-06 05:51:42 +0000383 std::unique_ptr<SpecialCaseList> BL;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000384 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
385 Type *IntptrTy;
386 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000387 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000388 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000389 Function *AsanPoisonGlobals;
390 Function *AsanUnpoisonGlobals;
391 Function *AsanRegisterGlobals;
392 Function *AsanUnregisterGlobals;
Evgeniy Stepanov47b1a952014-05-27 12:39:31 +0000393 Function *AsanCovModuleInit;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000394};
395
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000396// Stack poisoning does not play well with exception handling.
397// When an exception is thrown, we essentially bypass the code
398// that unpoisones the stack. This is why the run-time library has
399// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
400// stack in the interceptor. This however does not work inside the
401// actual function which catches the exception. Most likely because the
402// compiler hoists the load of the shadow value somewhere too high.
403// This causes asan to report a non-existing bug on 453.povray.
404// It sounds like an LLVM bug.
405struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
406 Function &F;
407 AddressSanitizer &ASan;
408 DIBuilder DIB;
409 LLVMContext *C;
410 Type *IntptrTy;
411 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000412 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000413
414 SmallVector<AllocaInst*, 16> AllocaVec;
415 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000416 unsigned StackAlignment;
417
Kostya Serebryany6805de52013-09-10 13:16:56 +0000418 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
419 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000420 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
421
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000422 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
423 struct AllocaPoisonCall {
424 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000425 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000426 uint64_t Size;
427 bool DoPoison;
428 };
429 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
430
431 // Maps Value to an AllocaInst from which the Value is originated.
432 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
433 AllocaForValueMapTy AllocaForValue;
434
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000435 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
436 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
437 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000438 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000439 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000440
441 bool runOnFunction() {
442 if (!ClStack) return false;
443 // Collect alloca, ret, lifetime instructions etc.
David Blaikieceec2bd2014-04-11 01:50:01 +0000444 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000445 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000446
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000447 if (AllocaVec.empty()) return false;
448
449 initializeCallbacks(*F.getParent());
450
451 poisonStack();
452
453 if (ClDebugStack) {
454 DEBUG(dbgs() << F);
455 }
456 return true;
457 }
458
459 // Finds all static Alloca instructions and puts
460 // poisoned red zones around all of them.
461 // Then unpoison everything back before the function returns.
462 void poisonStack();
463
464 // ----------------------- Visitors.
465 /// \brief Collect all Ret instructions.
466 void visitReturnInst(ReturnInst &RI) {
467 RetVec.push_back(&RI);
468 }
469
470 /// \brief Collect Alloca instructions we want (and can) handle.
471 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000472 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000473
474 StackAlignment = std::max(StackAlignment, AI.getAlignment());
475 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000476 }
477
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000478 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
479 /// errors.
480 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000481 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000482 Intrinsic::ID ID = II.getIntrinsicID();
483 if (ID != Intrinsic::lifetime_start &&
484 ID != Intrinsic::lifetime_end)
485 return;
486 // Found lifetime intrinsic, add ASan instrumentation if necessary.
487 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
488 // If size argument is undefined, don't do anything.
489 if (Size->isMinusOne()) return;
490 // Check that size doesn't saturate uint64_t and can
491 // be stored in IntptrTy.
492 const uint64_t SizeValue = Size->getValue().getLimitedValue();
493 if (SizeValue == ~0ULL ||
494 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
495 return;
496 // Find alloca instruction that corresponds to llvm.lifetime argument.
497 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
498 if (!AI) return;
499 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000500 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000501 AllocaPoisonCallVec.push_back(APC);
502 }
503
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000504 // ---------------------- Helpers.
505 void initializeCallbacks(Module &M);
506
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000507 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000508 bool isInterestingAlloca(AllocaInst &AI) const {
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000509 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
510 AI.getAllocatedType()->isSized() &&
511 // alloca() may be called with 0 size, ignore it.
512 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000513 }
514
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000515 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000516 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000517 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000518 return SizeInBytes;
519 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000520 /// Finds alloca where the value comes from.
521 AllocaInst *findAllocaForValue(Value *V);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000522 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000523 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000524 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000525
526 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
527 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000528};
529
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000530} // namespace
531
532char AddressSanitizer::ID = 0;
533INITIALIZE_PASS(AddressSanitizer, "asan",
534 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
535 false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000536FunctionPass *llvm::createAddressSanitizerFunctionPass() {
537 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000538}
539
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000540char AddressSanitizerModule::ID = 0;
541INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
542 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
543 "ModulePass", false, false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000544ModulePass *llvm::createAddressSanitizerModulePass(StringRef BlacklistFile) {
545 return new AddressSanitizerModule(BlacklistFile);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000546}
547
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000548static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000549 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000550 assert(Res < kNumberOfAccessSizes);
551 return Res;
552}
553
Bill Wendling58f8cef2013-08-06 22:52:42 +0000554// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000555static GlobalVariable *createPrivateGlobalForString(
556 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000557 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000558 // We use private linkage for module-local strings. If they can be merged
559 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000560 GlobalVariable *GV =
561 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000562 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
563 if (AllowMerging)
564 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000565 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
566 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000567}
568
569static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
570 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000571}
572
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000573Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
574 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000575 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
576 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000577 return Shadow;
578 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000579 if (Mapping.OrShadowOffset)
580 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
581 else
582 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000583}
584
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000585// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000586void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
587 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000588 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000589 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000590 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
591 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
592 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
593 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
594 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000595 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000596 AsanMemset,
597 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
598 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
599 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000600 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000601 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000602}
603
Kostya Serebryany90241602012-05-30 09:04:06 +0000604// If I is an interesting memory access, return the PointerOperand
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000605// and set IsWrite/Alignment. Otherwise return NULL.
606static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
607 unsigned *Alignment) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000608 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000609 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000610 *IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000611 *Alignment = LI->getAlignment();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000612 return LI->getPointerOperand();
613 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000614 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000615 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000616 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000617 *Alignment = SI->getAlignment();
Kostya Serebryany90241602012-05-30 09:04:06 +0000618 return SI->getPointerOperand();
619 }
620 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000621 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000622 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000623 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000624 return RMW->getPointerOperand();
625 }
626 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000627 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000628 *IsWrite = true;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000629 *Alignment = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +0000630 return XCHG->getPointerOperand();
631 }
Craig Topperf40110f2014-04-25 05:29:35 +0000632 return nullptr;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000633}
634
Kostya Serebryany796f6552014-02-27 12:45:36 +0000635static bool isPointerOperand(Value *V) {
636 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
637}
638
639// This is a rough heuristic; it may cause both false positives and
640// false negatives. The proper implementation requires cooperation with
641// the frontend.
642static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
643 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
644 if (!Cmp->isRelational())
645 return false;
646 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +0000647 if (BO->getOpcode() != Instruction::Sub)
Kostya Serebryany796f6552014-02-27 12:45:36 +0000648 return false;
649 } else {
650 return false;
651 }
652 if (!isPointerOperand(I->getOperand(0)) ||
653 !isPointerOperand(I->getOperand(1)))
654 return false;
655 return true;
656}
657
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000658bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
659 // If a global variable does not have dynamic initialization we don't
660 // have to instrument it. However, if a global does not have initializer
661 // at all, we assume it has dynamic initializer (in other TU).
662 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
663}
664
Kostya Serebryany796f6552014-02-27 12:45:36 +0000665void
666AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
667 IRBuilder<> IRB(I);
668 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
669 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
670 for (int i = 0; i < 2; i++) {
671 if (Param[i]->getType()->isPointerTy())
672 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
673 }
674 IRB.CreateCall2(F, Param[0], Param[1]);
675}
676
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000677void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann4a127062012-09-17 14:20:57 +0000678 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000679 unsigned Alignment = 0;
680 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000681 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000682 if (ClOpt && ClOptGlobals) {
683 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
684 // If initialization order checking is disabled, a simple access to a
685 // dynamically initialized global is always valid.
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000686 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000687 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000688 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000689 }
690 }
691 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
692 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
693 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
694 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
695 NumOptimizedAccessesToGlobalArray++;
696 return;
697 }
698 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000699 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000700 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000701
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000702 Type *OrigPtrTy = Addr->getType();
703 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
704
705 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000706 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000707
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000708 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000709
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000710 if (IsWrite)
711 NumInstrumentedWrites++;
712 else
713 NumInstrumentedReads++;
714
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000715 unsigned Granularity = 1 << Mapping.Scale;
716 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
717 // if the data is properly aligned.
718 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
719 TypeSize == 128) &&
720 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000721 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000722 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000723 // We can not do it with a single check, so we do 1-byte check for the first
724 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
725 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000726 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000727 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000728 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
729 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000730 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000731 } else {
732 Value *LastByte = IRB.CreateIntToPtr(
733 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
734 OrigPtrTy);
735 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
736 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
737 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000738}
739
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000740// Validate the result of Module::getOrInsertFunction called for an interface
741// function of AddressSanitizer. If the instrumented module defines a function
742// with the same name, their prototypes must match, otherwise
743// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000744static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000745 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
746 FuncOrBitcast->dump();
747 report_fatal_error("trying to redefine an AddressSanitizer "
748 "interface function");
749}
750
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000751Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000752 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000753 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000754 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000755 CallInst *Call = SizeArgument
756 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
757 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
758
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000759 // We don't do Call->setDoesNotReturn() because the BB already has
760 // UnreachableInst at the end.
761 // This EmptyAsm is required to avoid callback merge.
762 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000763 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000764}
765
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000766Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000767 Value *ShadowValue,
768 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000769 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000770 // Addr & (Granularity - 1)
771 Value *LastAccessedByte = IRB.CreateAnd(
772 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
773 // (Addr & (Granularity - 1)) + size - 1
774 if (TypeSize / 8 > 1)
775 LastAccessedByte = IRB.CreateAdd(
776 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
777 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
778 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000779 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000780 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
781 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
782}
783
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000784void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000785 Instruction *InsertBefore, Value *Addr,
786 uint32_t TypeSize, bool IsWrite,
787 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000788 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000789 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000790 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
791
792 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +0000793 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
794 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000795 return;
796 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000797
798 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000799 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000800 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
801 Value *ShadowPtr = memToShadow(AddrLong, IRB);
802 Value *CmpVal = Constant::getNullValue(ShadowTy);
803 Value *ShadowValue = IRB.CreateLoad(
804 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
805
806 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000807 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +0000808 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000809
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000810 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000811 TerminatorInst *CheckTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000812 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000813 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000814 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000815 IRB.SetInsertPoint(CheckTerm);
816 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000817 BasicBlock *CrashBlock =
818 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000819 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000820 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
821 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000822 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000823 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000824 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000825
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000826 Instruction *Crash = generateCrashCode(
827 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000828 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000829}
830
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000831void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
832 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000833 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000834 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000835
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000836 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000837 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
838 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000839
840 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000841 for (auto &BB : GlobalInit.getBasicBlockList())
842 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000843 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000844}
845
846void AddressSanitizerModule::createInitializerPoisonCalls(
847 Module &M, GlobalValue *ModuleName) {
848 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
849
850 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
851 for (Use &OP : CA->operands()) {
852 if (isa<ConstantAggregateZero>(OP))
853 continue;
854 ConstantStruct *CS = cast<ConstantStruct>(OP);
855
856 // Must have a function or null ptr.
857 // (CS->getOperand(0) is the init priority.)
858 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
859 if (F->getName() != kAsanModuleCtorName)
860 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000861 }
862 }
863}
864
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000865bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000866 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +0000867 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000868
Kostya Serebryany2fa38f82012-09-05 07:29:56 +0000869 if (BL->isIn(*G)) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000870 if (!Ty->isSized()) return false;
871 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000872 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000873 // Touch only those globals that will not be defined in other modules.
874 // Don't handle ODR type linkages since other modules may be built w/o asan.
875 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
876 G->getLinkage() != GlobalVariable::PrivateLinkage &&
877 G->getLinkage() != GlobalVariable::InternalLinkage)
878 return false;
879 // Two problems with thread-locals:
880 // - The address of the main thread's copy can't be computed at link-time.
881 // - Need to poison all copies, not just the main thread's one.
882 if (G->isThreadLocal())
883 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000884 // For now, just ignore this Global if the alignment is large.
885 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000886
887 // Ignore all the globals with the names starting with "\01L_OBJC_".
888 // Many of those are put into the .cstring section. The linker compresses
889 // that section by removing the spare \0s after the string terminator, so
890 // our redzones get broken.
891 if ((G->getName().find("\01L_OBJC_") == 0) ||
892 (G->getName().find("\01l_OBJC_") == 0)) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000893 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000894 return false;
895 }
896
897 if (G->hasSection()) {
898 StringRef Section(G->getSection());
899 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
900 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
901 // them.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000902 if (Section.startswith("__OBJC,") ||
903 Section.startswith("__DATA, __objc_")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000904 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000905 return false;
906 }
907 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
908 // Constant CFString instances are compiled in the following way:
909 // -- the string buffer is emitted into
910 // __TEXT,__cstring,cstring_literals
911 // -- the constant NSConstantString structure referencing that buffer
912 // is placed into __DATA,__cfstring
913 // Therefore there's no point in placing redzones into __DATA,__cfstring.
914 // Moreover, it causes the linker to crash on OS X 10.7
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000915 if (Section.startswith("__DATA,__cfstring")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000916 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
917 return false;
918 }
919 // The linker merges the contents of cstring_literals and removes the
920 // trailing zeroes.
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000921 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Alexander Potapenkob76ea322014-03-14 10:41:49 +0000922 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000923 return false;
924 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +0000925
926 // Callbacks put into the CRT initializer/terminator sections
927 // should not be instrumented.
928 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
929 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
930 if (Section.startswith(".CRT")) {
931 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
932 return false;
933 }
934
Alexander Potapenko04969e82014-03-20 10:48:34 +0000935 // Globals from llvm.metadata aren't emitted, do not instrument them.
936 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000937 }
938
939 return true;
940}
941
Alexey Samsonov788381b2012-12-25 12:28:20 +0000942void AddressSanitizerModule::initializeCallbacks(Module &M) {
943 IRBuilder<> IRB(*C);
944 // Declare our poisoning and unpoisoning functions.
945 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000946 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov788381b2012-12-25 12:28:20 +0000947 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
948 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
949 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
950 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
951 // Declare functions that register/unregister globals.
952 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
953 kAsanRegisterGlobalsName, IRB.getVoidTy(),
954 IntptrTy, IntptrTy, NULL));
955 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
956 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
957 kAsanUnregisterGlobalsName,
958 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
959 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov47b1a952014-05-27 12:39:31 +0000960 AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
961 kAsanCovModuleInitName,
962 IRB.getVoidTy(), IntptrTy, NULL));
963 AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +0000964}
965
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000966// This function replaces all global variables with new variables that have
967// trailing redzones. It also creates a function that poisons
968// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000969bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov788381b2012-12-25 12:28:20 +0000970 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000971
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000972 SmallVector<GlobalVariable *, 16> GlobalsToChange;
973
Alexey Samsonova02e6642014-05-29 18:40:48 +0000974 for (auto &G : M.globals()) {
975 if (ShouldInstrumentGlobal(&G))
976 GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000977 }
978
979 size_t n = GlobalsToChange.size();
980 if (n == 0) return false;
981
982 // A global is described by a structure
983 // size_t beg;
984 // size_t size;
985 // size_t size_with_redzone;
986 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +0000987 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000988 // size_t has_dynamic_init;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000989 // We initialize an array of such structures and pass it to a run-time call.
990 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000991 IntptrTy, IntptrTy,
Kostya Serebryanybd016bb2013-03-18 08:05:29 +0000992 IntptrTy, IntptrTy, NULL);
Rafael Espindola44fee4e2013-10-01 13:32:03 +0000993 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000994
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000995 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000996
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000997 // We shouldn't merge same module names, as this string serves as unique
998 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000999 GlobalVariable *ModuleName = createPrivateGlobalForString(
1000 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001001
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001002 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001003 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001004 GlobalVariable *G = GlobalsToChange[i];
1005 PointerType *PtrTy = cast<PointerType>(G->getType());
1006 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001007 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001008 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001009 // MinRZ <= RZ <= kMaxGlobalRedzone
1010 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001011 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +00001012 std::min(kMaxGlobalRedzone,
1013 (SizeInBytes / MinRZ / 4) * MinRZ));
1014 uint64_t RightRedzoneSize = RZ;
1015 // Round up to MinRZ
1016 if (SizeInBytes % MinRZ)
1017 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1018 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001019 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001020 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +00001021 bool GlobalHasDynamicInitializer =
1022 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001023
1024 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1025 Constant *NewInitializer = ConstantStruct::get(
1026 NewTy, G->getInitializer(),
1027 Constant::getNullValue(RightRedZoneTy), NULL);
1028
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001029 GlobalVariable *Name =
1030 createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001031
1032 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001033 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1034 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1035 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001036 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001037 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001038 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001039 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001040 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001041
1042 Value *Indices2[2];
1043 Indices2[0] = IRB.getInt32(0);
1044 Indices2[1] = IRB.getInt32(0);
1045
1046 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001047 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001048 NewGlobal->takeName(G);
1049 G->eraseFromParent();
1050
1051 Initializers[i] = ConstantStruct::get(
1052 GlobalStructTy,
1053 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1054 ConstantInt::get(IntptrTy, SizeInBytes),
1055 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1056 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001057 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001058 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001059 NULL);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001060
1061 // Populate the first and last globals declared in this TU.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001062 if (ClInitializers && GlobalHasDynamicInitializer)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001063 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001064
Kostya Serebryany20343352012-10-17 13:40:06 +00001065 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001066 }
1067
1068 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1069 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001070 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001071 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1072
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001073 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001074 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001075 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001076 IRB.CreateCall2(AsanRegisterGlobals,
1077 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1078 ConstantInt::get(IntptrTy, n));
1079
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001080 // We also need to unregister globals at the end, e.g. when a shared library
1081 // gets closed.
1082 Function *AsanDtorFunction = Function::Create(
1083 FunctionType::get(Type::getVoidTy(*C), false),
1084 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1085 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1086 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001087 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1088 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1089 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001090 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001091
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001092 DEBUG(dbgs() << M);
1093 return true;
1094}
1095
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001096bool AddressSanitizerModule::runOnModule(Module &M) {
1097 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1098 if (!DLP)
1099 return false;
1100 DL = &DLP->getDataLayout();
1101 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1102 C = &(M.getContext());
1103 int LongSize = DL->getPointerSizeInBits();
1104 IntptrTy = Type::getIntNTy(*C, LongSize);
1105 Mapping = getShadowMapping(M, LongSize);
1106 initializeCallbacks(M);
1107
1108 bool Changed = false;
1109
1110 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1111 assert(CtorFunc);
1112 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1113
1114 if (ClCoverage > 0) {
1115 Function *CovFunc = M.getFunction(kAsanCovName);
1116 int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1117 IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1118 Changed = true;
1119 }
1120
1121 if (ClGlobals && !BL->isIn(M)) Changed |= InstrumentGlobals(IRB, M);
1122
1123 return Changed;
1124}
1125
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001126void AddressSanitizer::initializeCallbacks(Module &M) {
1127 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001128 // Create __asan_report* callbacks.
1129 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1130 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1131 AccessSizeIndex++) {
1132 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001133 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001134 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001135 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001136 checkInterfaceFunction(
1137 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1138 IRB.getVoidTy(), IntptrTy, NULL));
1139 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1140 checkInterfaceFunction(
1141 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1142 IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001143 }
1144 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001145 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1146 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1147 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1148 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001149
Kostya Serebryany86332c02014-04-21 07:10:43 +00001150 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1151 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1152 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1153 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1154 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1155 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1156
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001157 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1158 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1159 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1160 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1161 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1162 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1163 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1164 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1165 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1166
1167 AsanHandleNoReturnFunc = checkInterfaceFunction(
1168 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Bob Wilsonda4147c2013-11-15 07:16:09 +00001169 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001170 kAsanCovName, IRB.getVoidTy(), NULL));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001171 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1172 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1173 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1174 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001175 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1176 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1177 StringRef(""), StringRef(""),
1178 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001179}
1180
1181// virtual
1182bool AddressSanitizer::doInitialization(Module &M) {
1183 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001184 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1185 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +00001186 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +00001187 DL = &DLP->getDataLayout();
1188
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001189 DynamicallyInitializedGlobals.Init(M);
1190
1191 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001192 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001193 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001194
1195 AsanCtorFunction = Function::Create(
1196 FunctionType::get(Type::getVoidTy(*C), false),
1197 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1198 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1199 // call __asan_init in the module ctor.
1200 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1201 AsanInitFunction = checkInterfaceFunction(
1202 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1203 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1204 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001205
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001206 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001207
Alexey Samsonov1f647502014-05-29 01:10:14 +00001208 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001209 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001210}
1211
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001212bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1213 // For each NSObject descendant having a +load method, this method is invoked
1214 // by the ObjC runtime before any of the static constructors is called.
1215 // Therefore we need to instrument such methods with a call to __asan_init
1216 // at the beginning in order to initialize our runtime before any access to
1217 // the shadow memory.
1218 // We cannot just ignore these methods, because they may call other
1219 // instrumented functions.
1220 if (F.getName().find(" load]") != std::string::npos) {
1221 IRBuilder<> IRB(F.begin()->begin());
1222 IRB.CreateCall(AsanInitFunction);
1223 return true;
1224 }
1225 return false;
1226}
1227
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001228void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1229 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001230 // Skip static allocas at the top of the entry block so they don't become
1231 // dynamic when we split the block. If we used our optimized stack layout,
1232 // then there will only be one alloca and it will come first.
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001233 for (; IP != BE; ++IP) {
1234 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1235 if (!AI || !AI->isStaticAlloca())
1236 break;
1237 }
1238
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001239 DebugLoc EntryLoc = IP->getDebugLoc().getFnDebugLoc(*C);
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001240 IRBuilder<> IRB(IP);
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001241 IRB.SetCurrentDebugLocation(EntryLoc);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001242 Type *Int8Ty = IRB.getInt8Ty();
1243 GlobalVariable *Guard = new GlobalVariable(
Kostya Serebryany0604c622013-11-15 09:52:05 +00001244 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Bob Wilsonda4147c2013-11-15 07:16:09 +00001245 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1246 LoadInst *Load = IRB.CreateLoad(Guard);
1247 Load->setAtomic(Monotonic);
1248 Load->setAlignment(1);
1249 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001250 Instruction *Ins = SplitBlockAndInsertIfThen(
1251 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Bob Wilsonda4147c2013-11-15 07:16:09 +00001252 IRB.SetInsertPoint(Ins);
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001253 IRB.SetCurrentDebugLocation(EntryLoc);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001254 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1255 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
Evgeniy Stepanov493df132014-06-05 14:34:45 +00001256 IRB.CreateCall(AsanCovFunction);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001257 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1258 Store->setAtomic(Monotonic);
1259 Store->setAlignment(1);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001260}
1261
1262// Poor man's coverage that works with ASan.
1263// We create a Guard boolean variable with the same linkage
1264// as the function and inject this code into the entry block (-asan-coverage=1)
1265// or all blocks (-asan-coverage=2):
1266// if (*Guard) {
1267// __sanitizer_cov(&F);
1268// *Guard = 1;
1269// }
1270// The accesses to Guard are atomic. The rest of the logic is
1271// in __sanitizer_cov (it's fine to call it more than once).
1272//
1273// This coverage implementation provides very limited data:
1274// it only tells if a given function (block) was ever executed.
1275// No counters, no per-edge data.
1276// But for many use cases this is what we need and the added slowdown
1277// is negligible. This simple implementation will probably be obsoleted
1278// by the upcoming Clang-based coverage implementation.
1279// By having it here and now we hope to
1280// a) get the functionality to users earlier and
1281// b) collect usage statistics to help improve Clang coverage design.
1282bool AddressSanitizer::InjectCoverage(Function &F,
1283 const ArrayRef<BasicBlock *> AllBlocks) {
1284 if (!ClCoverage) return false;
1285
Kostya Serebryany22e88102014-04-18 08:02:42 +00001286 if (ClCoverage == 1 ||
1287 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001288 InjectCoverageAtBlock(F, F.getEntryBlock());
1289 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001290 for (auto BB : AllBlocks)
1291 InjectCoverageAtBlock(F, *BB);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001292 }
Bob Wilsonda4147c2013-11-15 07:16:09 +00001293 return true;
1294}
1295
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001296bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001297 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001298 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001299 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001300 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001301
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001302 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001303 maybeInsertAsanInitAtFunctionEntry(F);
1304
Alexey Samsonov6d8bab82014-06-02 18:08:27 +00001305 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001306 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001307
1308 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1309 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001310
1311 // We want to instrument every address only once per basic block (unless there
1312 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001313 SmallSet<Value*, 16> TempsToInstrument;
1314 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001315 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001316 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001317 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001318 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001319 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001320 unsigned Alignment;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001321
1322 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001323 for (auto &BB : F) {
1324 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001325 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001326 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001327 for (auto &Inst : BB) {
1328 if (LooksLikeCodeInBug11395(&Inst)) return false;
1329 if (Value *Addr =
1330 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001331 if (ClOpt && ClOptSameTemp) {
1332 if (!TempsToInstrument.insert(Addr))
1333 continue; // We've seen this temp in the current BB.
1334 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001335 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001336 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1337 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001338 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001339 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001340 // ok, take it.
1341 } else {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001342 if (isa<AllocaInst>(Inst))
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001343 NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001344 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001345 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001346 // A call inside BB.
1347 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001348 if (CS.doesNotReturn())
1349 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001350 }
1351 continue;
1352 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001353 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001354 NumInsnsPerBB++;
1355 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1356 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001357 }
1358 }
1359
Craig Topperf40110f2014-04-25 05:29:35 +00001360 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001361 bool LikelyToInstrument =
1362 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1363 if (ClKeepUninstrumented && LikelyToInstrument) {
1364 ValueToValueMapTy VMap;
1365 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1366 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1367 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1368 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1369 }
1370
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001371 bool UseCalls = false;
1372 if (ClInstrumentationWithCallsThreshold >= 0 &&
1373 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1374 UseCalls = true;
1375
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001376 // Instrument.
1377 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001378 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001379 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1380 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001381 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001382 instrumentMop(Inst, UseCalls);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001383 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001384 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001385 }
1386 NumInstrumented++;
1387 }
1388
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001389 FunctionStackPoisoner FSP(F, *this);
1390 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001391
1392 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1393 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001394 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001395 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001396 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001397 }
1398
Alexey Samsonova02e6642014-05-29 18:40:48 +00001399 for (auto Inst : PointerComparisonsOrSubtracts) {
1400 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001401 NumInstrumented++;
1402 }
1403
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001404 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001405
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001406 if (InjectCoverage(F, AllBlocks))
Bob Wilsonda4147c2013-11-15 07:16:09 +00001407 res = true;
1408
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001409 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1410
1411 if (ClKeepUninstrumented) {
1412 if (!res) {
1413 // No instrumentation is done, no need for the duplicate.
1414 if (UninstrumentedDuplicate)
1415 UninstrumentedDuplicate->eraseFromParent();
1416 } else {
1417 // The function was instrumented. We must have the duplicate.
1418 assert(UninstrumentedDuplicate);
1419 UninstrumentedDuplicate->setSection("NOASAN");
1420 assert(!F.hasSection());
1421 F.setSection("ASAN");
1422 }
1423 }
1424
1425 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001426}
1427
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001428// Workaround for bug 11395: we don't want to instrument stack in functions
1429// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1430// FIXME: remove once the bug 11395 is fixed.
1431bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1432 if (LongSize != 32) return false;
1433 CallInst *CI = dyn_cast<CallInst>(I);
1434 if (!CI || !CI->isInlineAsm()) return false;
1435 if (CI->getNumArgOperands() <= 5) return false;
1436 // We have inline assembly with quite a few arguments.
1437 return true;
1438}
1439
1440void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1441 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001442 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1443 std::string Suffix = itostr(i);
1444 AsanStackMallocFunc[i] = checkInterfaceFunction(
1445 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1446 IntptrTy, IntptrTy, NULL));
1447 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1448 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1449 IntptrTy, IntptrTy, NULL));
1450 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001451 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1452 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1453 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1454 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1455}
1456
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001457void
1458FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1459 IRBuilder<> &IRB, Value *ShadowBase,
1460 bool DoPoison) {
1461 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001462 size_t i = 0;
1463 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1464 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1465 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1466 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1467 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1468 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1469 uint64_t Val = 0;
1470 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001471 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001472 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1473 else
1474 Val = (Val << 8) | ShadowBytes[i + j];
1475 }
1476 if (!Val) continue;
1477 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1478 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1479 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1480 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001481 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001482 }
1483}
1484
Kostya Serebryany6805de52013-09-10 13:16:56 +00001485// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1486// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1487static int StackMallocSizeClass(uint64_t LocalStackSize) {
1488 assert(LocalStackSize <= kMaxStackMallocSize);
1489 uint64_t MaxSize = kMinStackMallocSize;
1490 for (int i = 0; ; i++, MaxSize *= 2)
1491 if (LocalStackSize <= MaxSize)
1492 return i;
1493 llvm_unreachable("impossible LocalStackSize");
1494}
1495
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001496// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1497// We can not use MemSet intrinsic because it may end up calling the actual
1498// memset. Size is a multiple of 8.
1499// Currently this generates 8-byte stores on x86_64; it may be better to
1500// generate wider stores.
1501void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1502 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1503 assert(!(Size % 8));
1504 assert(kAsanStackAfterReturnMagic == 0xf5);
1505 for (int i = 0; i < Size; i += 8) {
1506 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1507 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1508 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1509 }
1510}
1511
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001512static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001513 for (const auto &Inst : F.getEntryBlock())
1514 if (!isa<AllocaInst>(Inst))
1515 return Inst.getDebugLoc();
1516 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001517}
1518
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001519void FunctionStackPoisoner::poisonStack() {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001520 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001521 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001522
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001523 assert(AllocaVec.size() > 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001524 Instruction *InsBefore = AllocaVec[0];
1525 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001526 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001527
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001528 SmallVector<ASanStackVariableDescription, 16> SVD;
1529 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001530 for (AllocaInst *AI : AllocaVec) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001531 ASanStackVariableDescription D = { AI->getName().data(),
1532 getAllocaSizeInBytes(AI),
1533 AI->getAlignment(), AI, 0};
1534 SVD.push_back(D);
1535 }
1536 // Minimal header size (left redzone) is 4 pointers,
1537 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1538 size_t MinHeaderSize = ASan.LongSize / 2;
1539 ASanStackFrameLayout L;
1540 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1541 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1542 uint64_t LocalStackSize = L.FrameSize;
1543 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001544 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001545
1546 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1547 AllocaInst *MyAlloca =
1548 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001549 MyAlloca->setDebugLoc(EntryDebugLocation);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001550 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1551 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1552 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001553 assert(MyAlloca->isStaticAlloca());
1554 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1555 Value *LocalStackBase = OrigStackBase;
1556
1557 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001558 // LocalStackBase = OrigStackBase
1559 // if (__asan_option_detect_stack_use_after_return)
1560 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001561 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1562 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001563 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1564 kAsanOptionDetectUAR, IRB.getInt32Ty());
1565 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1566 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001567 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001568 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1569 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001570 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001571 LocalStackBase = IRBIf.CreateCall2(
1572 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001573 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001574 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1575 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001576 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001577 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1578 Phi->addIncoming(OrigStackBase, CmpBlock);
1579 Phi->addIncoming(LocalStackBase, SetBlock);
1580 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001581 }
1582
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001583 // Insert poison calls for lifetime intrinsics for alloca.
1584 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001585 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001586 assert(APC.InsBefore);
1587 assert(APC.AI);
1588 IRBuilder<> IRB(APC.InsBefore);
1589 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001590 HavePoisonedAllocas |= APC.DoPoison;
1591 }
1592
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001593 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001594 for (const auto &Desc : SVD) {
1595 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001596 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001597 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001598 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001599 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001600 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001601 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001602
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001603 // The left-most redzone has enough space for at least 4 pointers.
1604 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001605 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1606 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1607 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001608 // Write the frame description constant to redzone[1].
1609 Value *BasePlus1 = IRB.CreateIntToPtr(
1610 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1611 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001612 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001613 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1614 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001615 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1616 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001617 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001618 // Write the PC to redzone[2].
1619 Value *BasePlus2 = IRB.CreateIntToPtr(
1620 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1621 2 * ASan.LongSize/8)),
1622 IntptrPtrTy);
1623 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001624
1625 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001626 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001627 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001628
Kostya Serebryany530e2072013-12-23 14:15:08 +00001629 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001630 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001631 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001632 // Mark the current frame as retired.
1633 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1634 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001635 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001636 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001637 // if LocalStackBase != OrigStackBase:
1638 // // In use-after-return mode, poison the whole stack frame.
1639 // if StackMallocIdx <= 4
1640 // // For small sizes inline the whole thing:
1641 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1642 // **SavedFlagPtr(LocalStackBase) = 0
1643 // else
1644 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1645 // else
1646 // <This is not a fake stack; unpoison the redzones>
1647 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1648 TerminatorInst *ThenTerm, *ElseTerm;
1649 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1650
1651 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001652 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001653 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1654 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1655 ClassSize >> Mapping.Scale);
1656 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1657 LocalStackBase,
1658 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1659 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1660 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1661 IRBPoison.CreateStore(
1662 Constant::getNullValue(IRBPoison.getInt8Ty()),
1663 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1664 } else {
1665 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001666 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1667 ConstantInt::get(IntptrTy, LocalStackSize),
1668 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001669 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001670
1671 IRBuilder<> IRBElse(ElseTerm);
1672 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001673 } else if (HavePoisonedAllocas) {
1674 // If we poisoned some allocas in llvm.lifetime analysis,
1675 // unpoison whole stack frame now.
1676 assert(LocalStackBase == OrigStackBase);
1677 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001678 } else {
1679 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001680 }
1681 }
1682
Kostya Serebryany09959942012-10-19 06:20:53 +00001683 // We are done. Remove the old unused alloca instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001684 for (auto AI : AllocaVec)
1685 AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001686}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001687
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001688void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001689 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001690 // For now just insert the call to ASan runtime.
1691 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1692 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1693 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1694 : AsanUnpoisonStackMemoryFunc,
1695 AddrArg, SizeArg);
1696}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001697
1698// Handling llvm.lifetime intrinsics for a given %alloca:
1699// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1700// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1701// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1702// could be poisoned by previous llvm.lifetime.end instruction, as the
1703// variable may go in and out of scope several times, e.g. in loops).
1704// (3) if we poisoned at least one %alloca in a function,
1705// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001706
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001707AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1708 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1709 // We're intested only in allocas we can handle.
Craig Topperf40110f2014-04-25 05:29:35 +00001710 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001711 // See if we've already calculated (or started to calculate) alloca for a
1712 // given value.
1713 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1714 if (I != AllocaForValue.end())
1715 return I->second;
1716 // Store 0 while we're calculating alloca for value V to avoid
1717 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001718 AllocaForValue[V] = nullptr;
1719 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001720 if (CastInst *CI = dyn_cast<CastInst>(V))
1721 Res = findAllocaForValue(CI->getOperand(0));
1722 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1723 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1724 Value *IncValue = PN->getIncomingValue(i);
1725 // Allow self-referencing phi-nodes.
1726 if (IncValue == PN) continue;
1727 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1728 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001729 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1730 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001731 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001732 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001733 }
Craig Topperf40110f2014-04-25 05:29:35 +00001734 if (Res)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001735 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001736 return Res;
1737}