blob: 95fca75392af7a15b5008db24b7df71f53acc8ea [file] [log] [blame]
Kostya Serebryany800e03f2011-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 Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000019#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
Kostya Serebryany3386d252013-10-16 14:06:14 +000023#include "llvm/ADT/Statistic.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000024#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000025#include "llvm/ADT/Triple.h"
Stephen Hines36b56882014-04-23 16:57:46 -070026#include "llvm/IR/CallSite.h"
27#include "llvm/IR/DIBuilder.h"
Chandler Carruth0b8c9a82013-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"
Stephen Hines36b56882014-04-23 16:57:46 -070032#include "llvm/IR/InstVisitor.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000033#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
Stephen Hines36b56882014-04-23 16:57:46 -070035#include "llvm/IR/MDBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/DataTypes.h"
40#include "llvm/Support/Debug.h"
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000041#include "llvm/Support/Endian.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000042#include "llvm/Support/system_error.h"
Stephen Hines36b56882014-04-23 16:57:46 -070043#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany20985712013-06-26 09:18:17 +000045#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000046#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne405515d2013-07-09 22:02:49 +000048#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000049#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000050#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000051
52using namespace llvm;
53
Stephen Hinesdce4a402014-05-29 02:49:00 -070054#define DEBUG_TYPE "asan"
55
Kostya Serebryany800e03f2011-11-16 01:35:23 +000056static const uint64_t kDefaultShadowScale = 3;
57static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Stephen Hinesdce4a402014-05-29 02:49:00 -070058static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000059static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Stephen Hines36b56882014-04-23 16:57:46 -070060static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000061static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000062static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Stephen Hines36b56882014-04-23 16:57:46 -070063static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000066static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany800e03f2011-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 Topper4172a8a2013-07-16 01:17:10 +000071static const char *const kAsanModuleCtorName = "asan.module_ctor";
72static const char *const kAsanModuleDtorName = "asan.module_dtor";
73static const int kAsanCtorAndCtorPriority = 1;
74static 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 Samsonov48d7d1d2013-08-05 13:19:49 +000078static const char *const kAsanUnregisterGlobalsName =
79 "__asan_unregister_globals";
Craig Topper4172a8a2013-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";
Stephen Hinesdce4a402014-05-29 02:49:00 -070083static const char *const kAsanCovModuleInitName = "__sanitizer_cov_module_init";
Bob Wilson4b899142013-11-15 07:16:09 +000084static const char *const kAsanCovName = "__sanitizer_cov";
Stephen Hines36b56882014-04-23 16:57:46 -070085static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
86static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topper4172a8a2013-07-16 01:17:10 +000087static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryanyf3d4b352013-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 Topper4172a8a2013-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 Samsonovf985f442012-12-04 01:34:23 +000095 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000096
Kostya Serebryanyac04aba2013-09-18 14:07:14 +000097static const char *const kAsanOptionDetectUAR =
98 "__asan_option_detect_stack_use_after_return";
99
David Blaikie0b956502013-09-18 00:11:27 +0000100#ifndef NDEBUG
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000101static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikie0b956502013-09-18 00:11:27 +0000102#endif
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000103
Kostya Serebryanyc0ed3e52012-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 Serebryany800e03f2011-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 Serebryanye6cf2e02012-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 Serebryany6e2d5062012-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 Serebryanyc0ed3e52012-07-16 16:15:40 +0000120// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-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 Serebryany800e03f2011-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));
131// This flag may need to be replaced with -f[no]asan-use-after-return.
132static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
133 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
134// This flag may need to be replaced with -f[no]asan-globals.
135static cl::opt<bool> ClGlobals("asan-globals",
136 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Stephen Hines36b56882014-04-23 16:57:46 -0700137static cl::opt<int> ClCoverage("asan-coverage",
138 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
139 cl::Hidden, cl::init(false));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700140static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
141 cl::desc("Add coverage instrumentation only to the entry block if there "
142 "are more than this number of blocks."),
143 cl::Hidden, cl::init(1500));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000144static cl::opt<bool> ClInitializers("asan-initialization-order",
145 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Stephen Hines36b56882014-04-23 16:57:46 -0700146static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
147 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
148 cl::Hidden, cl::init(false));
149static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
150 cl::desc("Realign stack to the value of this flag (power of two)"),
151 cl::Hidden, cl::init(32));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000152static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
153 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000154 "during instrumentation"), cl::Hidden);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700155static cl::opt<int> ClInstrumentationWithCallsThreshold(
156 "asan-instrumentation-with-call-threshold",
157 cl::desc("If the function being instrumented contains more than "
158 "this number of memory accesses, use callbacks instead of "
159 "inline checks (-1 means never use callbacks)."),
160 cl::Hidden, cl::init(7000));
161static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
162 "asan-memory-access-callback-prefix",
163 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
164 cl::init("__asan_"));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000165
Kostya Serebryany20985712013-06-26 09:18:17 +0000166// This is an experimental feature that will allow to choose between
167// instrumented and non-instrumented code at link-time.
168// If this option is on, just before instrumenting a function we create its
169// clone; if the function is not changed by asan the clone is deleted.
170// If we end up with a clone, we put the instrumented function into a section
171// called "ASAN" and the uninstrumented function into a section called "NOASAN".
172//
173// This is still a prototype, we need to figure out a way to keep two copies of
174// a function so that the linker can easily choose one of them.
175static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
176 cl::desc("Keep uninstrumented copies of functions"),
177 cl::Hidden, cl::init(false));
178
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000179// These flags allow to change the shadow mapping.
180// The shadow mapping looks like
181// Shadow = (Mem >> scale) + (1 << offset_log)
182static cl::opt<int> ClMappingScale("asan-mapping-scale",
183 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000184
185// Optimization flags. Not user visible, used mostly for testing
186// and benchmarking the tool.
187static cl::opt<bool> ClOpt("asan-opt",
188 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
189static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
190 cl::desc("Instrument the same temp just once"), cl::Hidden,
191 cl::init(true));
192static cl::opt<bool> ClOptGlobals("asan-opt-globals",
193 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
194
Alexey Samsonovee548272012-11-29 18:14:24 +0000195static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
196 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
197 cl::Hidden, cl::init(false));
198
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000199// Debug flags.
200static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
201 cl::init(0));
202static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
203 cl::Hidden, cl::init(0));
204static cl::opt<std::string> ClDebugFunc("asan-debug-func",
205 cl::Hidden, cl::desc("Debug func"));
206static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
207 cl::Hidden, cl::init(-1));
208static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
209 cl::Hidden, cl::init(-1));
210
Kostya Serebryany3386d252013-10-16 14:06:14 +0000211STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
212STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
213STATISTIC(NumOptimizedAccessesToGlobalArray,
214 "Number of optimized accesses to global arrays");
215STATISTIC(NumOptimizedAccessesToGlobalVar,
216 "Number of optimized accesses to global vars");
217
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000218namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000219/// A set of dynamically initialized globals extracted from metadata.
220class SetOfDynamicallyInitializedGlobals {
221 public:
222 void Init(Module& M) {
223 // Clang generates metadata identifying all dynamically initialized globals.
224 NamedMDNode *DynamicGlobals =
225 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
226 if (!DynamicGlobals)
227 return;
228 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
229 MDNode *MDN = DynamicGlobals->getOperand(i);
230 assert(MDN->getNumOperands() == 1);
231 Value *VG = MDN->getOperand(0);
232 // The optimizer may optimize away a global entirely, in which case we
233 // cannot instrument access to it.
234 if (!VG)
235 continue;
236 DynInitGlobals.insert(cast<GlobalVariable>(VG));
237 }
238 }
239 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
240 private:
241 SmallSet<GlobalValue*, 32> DynInitGlobals;
242};
243
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000244/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000245/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000246struct ShadowMapping {
247 int Scale;
248 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000249 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000250};
251
Stephen Hines36b56882014-04-23 16:57:46 -0700252static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000253 llvm::Triple TargetTriple(M.getTargetTriple());
254 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700255 bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
Stephen Hines36b56882014-04-23 16:57:46 -0700256 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
257 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000258 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
259 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000260 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000261 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
262 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000263
264 ShadowMapping Mapping;
265
Stephen Hines36b56882014-04-23 16:57:46 -0700266 if (LongSize == 32) {
267 if (IsAndroid)
268 Mapping.Offset = 0;
269 else if (IsMIPS32)
270 Mapping.Offset = kMIPS32_ShadowOffset32;
271 else if (IsFreeBSD)
272 Mapping.Offset = kFreeBSD_ShadowOffset32;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700273 else if (IsIOS)
274 Mapping.Offset = kIOSShadowOffset32;
Stephen Hines36b56882014-04-23 16:57:46 -0700275 else
276 Mapping.Offset = kDefaultShadowOffset32;
277 } else { // LongSize == 64
278 if (IsPPC64)
279 Mapping.Offset = kPPC64_ShadowOffset64;
280 else if (IsFreeBSD)
281 Mapping.Offset = kFreeBSD_ShadowOffset64;
282 else if (IsLinux && IsX86_64)
283 Mapping.Offset = kSmallX86_64ShadowOffset;
284 else
285 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000286 }
287
288 Mapping.Scale = kDefaultShadowScale;
289 if (ClMappingScale) {
290 Mapping.Scale = ClMappingScale;
291 }
292
Stephen Hines36b56882014-04-23 16:57:46 -0700293 // OR-ing shadow offset if more efficient (at least on x86) if the offset
294 // is a power of two, but on ppc64 we have to use add since the shadow
295 // offset is not necessary 1/8-th of the address space.
296 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
297
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000298 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000299}
300
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000301static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000302 // Redzone used for stack and globals is at least 32 bytes.
303 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000304 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000305}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000306
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000307/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000308struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000309 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000310 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000311 bool CheckLifetime = false,
Stephen Hines36b56882014-04-23 16:57:46 -0700312 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000313 : FunctionPass(ID),
314 CheckInitOrder(CheckInitOrder || ClInitializers),
315 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000316 CheckLifetime(CheckLifetime || ClCheckLifetime),
317 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Stephen Hines36b56882014-04-23 16:57:46 -0700318 : BlacklistFile) {}
319 const char *getPassName() const override {
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000320 return "AddressSanitizerFunctionPass";
321 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700322 void instrumentMop(Instruction *I, bool UseCalls);
Stephen Hines36b56882014-04-23 16:57:46 -0700323 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000324 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
325 Value *Addr, uint32_t TypeSize, bool IsWrite,
Stephen Hinesdce4a402014-05-29 02:49:00 -0700326 Value *SizeArgument, bool UseCalls);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000327 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
328 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000329 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000330 bool IsWrite, size_t AccessSizeIndex,
331 Value *SizeArgument);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700332 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000333 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Stephen Hines36b56882014-04-23 16:57:46 -0700334 bool runOnFunction(Function &F) override;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000335 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Stephen Hines36b56882014-04-23 16:57:46 -0700336 bool doInitialization(Module &M) override;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000337 static char ID; // Pass identification, replacement for typeid
338
339 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000340 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000341
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000342 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany3386d252013-10-16 14:06:14 +0000343 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Stephen Hines36b56882014-04-23 16:57:46 -0700344 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
345 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000346
Alexey Samsonovee548272012-11-29 18:14:24 +0000347 bool CheckInitOrder;
348 bool CheckUseAfterReturn;
349 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000350 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000351
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000352 LLVMContext *C;
Stephen Hines36b56882014-04-23 16:57:46 -0700353 const DataLayout *DL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000354 int LongSize;
355 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000356 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000357 Function *AsanCtorFunction;
358 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000359 Function *AsanHandleNoReturnFunc;
Bob Wilson4b899142013-11-15 07:16:09 +0000360 Function *AsanCovFunction;
Stephen Hines36b56882014-04-23 16:57:46 -0700361 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
362 std::unique_ptr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000363 // This array is indexed by AccessIsWrite and log2(AccessSize).
364 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700365 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000366 // This array is indexed by AccessIsWrite.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700367 Function *AsanErrorCallbackSized[2],
368 *AsanMemoryAccessCallbackSized[2];
369 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000370 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000371 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000372
373 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000374};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000375
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000376class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000377 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000378 AddressSanitizerModule(bool CheckInitOrder = true,
Stephen Hines36b56882014-04-23 16:57:46 -0700379 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000380 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000381 CheckInitOrder(CheckInitOrder || ClInitializers),
382 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Stephen Hines36b56882014-04-23 16:57:46 -0700383 : BlacklistFile) {}
384 bool runOnModule(Module &M) override;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000385 static char ID; // Pass identification, replacement for typeid
Stephen Hines36b56882014-04-23 16:57:46 -0700386 const char *getPassName() const override {
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000387 return "AddressSanitizerModule";
388 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000389
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000390 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000391 void initializeCallbacks(Module &M);
392
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000393 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000394 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Stephen Hines36b56882014-04-23 16:57:46 -0700395 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000396 return RedzoneSizeForScale(Mapping.Scale);
397 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000398
Alexey Samsonovee548272012-11-29 18:14:24 +0000399 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000400 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000401
Stephen Hines36b56882014-04-23 16:57:46 -0700402 std::unique_ptr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000403 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
404 Type *IntptrTy;
405 LLVMContext *C;
Stephen Hines36b56882014-04-23 16:57:46 -0700406 const DataLayout *DL;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000407 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000408 Function *AsanPoisonGlobals;
409 Function *AsanUnpoisonGlobals;
410 Function *AsanRegisterGlobals;
411 Function *AsanUnregisterGlobals;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700412 Function *AsanCovModuleInit;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000413};
414
Alexey Samsonov59cca132012-12-25 12:04:36 +0000415// Stack poisoning does not play well with exception handling.
416// When an exception is thrown, we essentially bypass the code
417// that unpoisones the stack. This is why the run-time library has
418// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
419// stack in the interceptor. This however does not work inside the
420// actual function which catches the exception. Most likely because the
421// compiler hoists the load of the shadow value somewhere too high.
422// This causes asan to report a non-existing bug on 453.povray.
423// It sounds like an LLVM bug.
424struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
425 Function &F;
426 AddressSanitizer &ASan;
427 DIBuilder DIB;
428 LLVMContext *C;
429 Type *IntptrTy;
430 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000431 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000432
433 SmallVector<AllocaInst*, 16> AllocaVec;
434 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000435 unsigned StackAlignment;
436
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +0000437 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
438 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov59cca132012-12-25 12:04:36 +0000439 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
440
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000441 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
442 struct AllocaPoisonCall {
443 IntrinsicInst *InsBefore;
Alexey Samsonov64409ad2013-11-18 14:53:55 +0000444 AllocaInst *AI;
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000445 uint64_t Size;
446 bool DoPoison;
447 };
448 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
449
450 // Maps Value to an AllocaInst from which the Value is originated.
451 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
452 AllocaForValueMapTy AllocaForValue;
453
Alexey Samsonov59cca132012-12-25 12:04:36 +0000454 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
455 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
456 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000457 Mapping(ASan.Mapping),
Stephen Hines36b56882014-04-23 16:57:46 -0700458 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000459
460 bool runOnFunction() {
461 if (!ClStack) return false;
462 // Collect alloca, ret, lifetime instructions etc.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700463 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Alexey Samsonov59cca132012-12-25 12:04:36 +0000464 visit(*BB);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700465
Alexey Samsonov59cca132012-12-25 12:04:36 +0000466 if (AllocaVec.empty()) return false;
467
468 initializeCallbacks(*F.getParent());
469
470 poisonStack();
471
472 if (ClDebugStack) {
473 DEBUG(dbgs() << F);
474 }
475 return true;
476 }
477
478 // Finds all static Alloca instructions and puts
479 // poisoned red zones around all of them.
480 // Then unpoison everything back before the function returns.
481 void poisonStack();
482
483 // ----------------------- Visitors.
484 /// \brief Collect all Ret instructions.
485 void visitReturnInst(ReturnInst &RI) {
486 RetVec.push_back(&RI);
487 }
488
489 /// \brief Collect Alloca instructions we want (and can) handle.
490 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000491 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000492
493 StackAlignment = std::max(StackAlignment, AI.getAlignment());
494 AllocaVec.push_back(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000495 }
496
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000497 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
498 /// errors.
499 void visitIntrinsicInst(IntrinsicInst &II) {
500 if (!ASan.CheckLifetime) return;
501 Intrinsic::ID ID = II.getIntrinsicID();
502 if (ID != Intrinsic::lifetime_start &&
503 ID != Intrinsic::lifetime_end)
504 return;
505 // Found lifetime intrinsic, add ASan instrumentation if necessary.
506 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
507 // If size argument is undefined, don't do anything.
508 if (Size->isMinusOne()) return;
509 // Check that size doesn't saturate uint64_t and can
510 // be stored in IntptrTy.
511 const uint64_t SizeValue = Size->getValue().getLimitedValue();
512 if (SizeValue == ~0ULL ||
513 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
514 return;
515 // Find alloca instruction that corresponds to llvm.lifetime argument.
516 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
517 if (!AI) return;
518 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonov64409ad2013-11-18 14:53:55 +0000519 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000520 AllocaPoisonCallVec.push_back(APC);
521 }
522
Alexey Samsonov59cca132012-12-25 12:04:36 +0000523 // ---------------------- Helpers.
524 void initializeCallbacks(Module &M);
525
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000526 // Check if we want (and can) handle this alloca.
Jakub Staszak4c710642013-08-09 20:53:48 +0000527 bool isInterestingAlloca(AllocaInst &AI) const {
Stephen Hines36b56882014-04-23 16:57:46 -0700528 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
529 AI.getAllocatedType()->isSized() &&
530 // alloca() may be called with 0 size, ignore it.
531 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000532 }
533
Jakub Staszak4c710642013-08-09 20:53:48 +0000534 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000535 Type *Ty = AI->getAllocatedType();
Stephen Hines36b56882014-04-23 16:57:46 -0700536 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000537 return SizeInBytes;
538 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000539 /// Finds alloca where the value comes from.
540 AllocaInst *findAllocaForValue(Value *V);
Stephen Hines36b56882014-04-23 16:57:46 -0700541 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov59cca132012-12-25 12:04:36 +0000542 Value *ShadowBase, bool DoPoison);
Jakub Staszak4c710642013-08-09 20:53:48 +0000543 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000544
545 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
546 int Size);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000547};
548
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000549} // namespace
550
551char AddressSanitizer::ID = 0;
552INITIALIZE_PASS(AddressSanitizer, "asan",
553 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
554 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000555FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000556 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Stephen Hines36b56882014-04-23 16:57:46 -0700557 StringRef BlacklistFile) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000558 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Stephen Hines36b56882014-04-23 16:57:46 -0700559 CheckLifetime, BlacklistFile);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000560}
561
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000562char AddressSanitizerModule::ID = 0;
563INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
564 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
565 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000566ModulePass *llvm::createAddressSanitizerModulePass(
Stephen Hines36b56882014-04-23 16:57:46 -0700567 bool CheckInitOrder, StringRef BlacklistFile) {
568 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
Alexander Potapenko25878042012-01-23 11:22:43 +0000569}
570
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000571static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000572 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000573 assert(Res < kNumberOfAccessSizes);
574 return Res;
575}
576
Bill Wendling55a1a592013-08-06 22:52:42 +0000577// \brief Create a constant for Str so that we can pass it to the run-time lib.
Stephen Hines36b56882014-04-23 16:57:46 -0700578static GlobalVariable *createPrivateGlobalForString(
579 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000580 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Stephen Hines36b56882014-04-23 16:57:46 -0700581 // We use private linkage for module-local strings. If they can be merged
582 // with another one, we set the unnamed_addr attribute.
583 GlobalVariable *GV =
584 new GlobalVariable(M, StrConst->getType(), true,
585 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
586 if (AllowMerging)
587 GV->setUnnamedAddr(true);
Kostya Serebryany51116272013-03-18 09:38:39 +0000588 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
589 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000590}
591
592static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
593 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000594}
595
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000596Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
597 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000598 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
599 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000600 return Shadow;
601 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000602 if (Mapping.OrShadowOffset)
603 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
604 else
605 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000606}
607
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000608// Instrument memset/memmove/memcpy
Stephen Hinesdce4a402014-05-29 02:49:00 -0700609void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
610 IRBuilder<> IRB(MI);
611 if (isa<MemTransferInst>(MI)) {
612 IRB.CreateCall3(
613 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
614 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
615 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
616 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
617 } else if (isa<MemSetInst>(MI)) {
618 IRB.CreateCall3(
619 AsanMemset,
620 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
621 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
622 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000623 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700624 MI->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000625}
626
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000627// If I is an interesting memory access, return the PointerOperand
Stephen Hinesdce4a402014-05-29 02:49:00 -0700628// and set IsWrite/Alignment. Otherwise return NULL.
629static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
630 unsigned *Alignment) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000631 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700632 if (!ClInstrumentReads) return nullptr;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000633 *IsWrite = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700634 *Alignment = LI->getAlignment();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000635 return LI->getPointerOperand();
636 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000637 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700638 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000639 *IsWrite = true;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700640 *Alignment = SI->getAlignment();
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000641 return SI->getPointerOperand();
642 }
643 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700644 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000645 *IsWrite = true;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700646 *Alignment = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000647 return RMW->getPointerOperand();
648 }
649 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700650 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000651 *IsWrite = true;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700652 *Alignment = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000653 return XCHG->getPointerOperand();
654 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700655 return nullptr;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000656}
657
Stephen Hines36b56882014-04-23 16:57:46 -0700658static bool isPointerOperand(Value *V) {
659 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
660}
661
662// This is a rough heuristic; it may cause both false positives and
663// false negatives. The proper implementation requires cooperation with
664// the frontend.
665static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
666 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
667 if (!Cmp->isRelational())
668 return false;
669 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
670 if (BO->getOpcode() != Instruction::Sub)
671 return false;
672 } else {
673 return false;
674 }
675 if (!isPointerOperand(I->getOperand(0)) ||
676 !isPointerOperand(I->getOperand(1)))
677 return false;
678 return true;
679}
680
Kostya Serebryany3386d252013-10-16 14:06:14 +0000681bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
682 // If a global variable does not have dynamic initialization we don't
683 // have to instrument it. However, if a global does not have initializer
684 // at all, we assume it has dynamic initializer (in other TU).
685 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
686}
687
Stephen Hines36b56882014-04-23 16:57:46 -0700688void
689AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
690 IRBuilder<> IRB(I);
691 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
692 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
693 for (int i = 0; i < 2; i++) {
694 if (Param[i]->getType()->isPointerTy())
695 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
696 }
697 IRB.CreateCall2(F, Param[0], Param[1]);
698}
699
Stephen Hinesdce4a402014-05-29 02:49:00 -0700700void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000701 bool IsWrite = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700702 unsigned Alignment = 0;
703 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000704 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000705 if (ClOpt && ClOptGlobals) {
706 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
707 // If initialization order checking is disabled, a simple access to a
708 // dynamically initialized global is always valid.
Kostya Serebryany3386d252013-10-16 14:06:14 +0000709 if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
710 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000711 return;
Kostya Serebryany3386d252013-10-16 14:06:14 +0000712 }
713 }
714 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
715 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
716 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
717 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
718 NumOptimizedAccessesToGlobalArray++;
719 return;
720 }
721 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000722 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000723 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000724
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000725 Type *OrigPtrTy = Addr->getType();
726 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
727
728 assert(OrigTy->isSized());
Stephen Hines36b56882014-04-23 16:57:46 -0700729 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000730
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000731 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000732
Kostya Serebryany3386d252013-10-16 14:06:14 +0000733 if (IsWrite)
734 NumInstrumentedWrites++;
735 else
736 NumInstrumentedReads++;
737
Stephen Hinesdce4a402014-05-29 02:49:00 -0700738 unsigned Granularity = 1 << Mapping.Scale;
739 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
740 // if the data is properly aligned.
741 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
742 TypeSize == 128) &&
743 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
744 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
745 // Instrument unusual size or unusual alignment.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000746 // We can not do it with a single check, so we do 1-byte check for the first
747 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
748 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000749 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000750 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700751 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
752 if (UseCalls) {
753 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
754 } else {
755 Value *LastByte = IRB.CreateIntToPtr(
756 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
757 OrigPtrTy);
758 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
759 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
760 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000761}
762
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000763// Validate the result of Module::getOrInsertFunction called for an interface
764// function of AddressSanitizer. If the instrumented module defines a function
765// with the same name, their prototypes must match, otherwise
766// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000767static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000768 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
769 FuncOrBitcast->dump();
770 report_fatal_error("trying to redefine an AddressSanitizer "
771 "interface function");
772}
773
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000774Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000775 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000776 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000777 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000778 CallInst *Call = SizeArgument
779 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
780 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
781
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000782 // We don't do Call->setDoesNotReturn() because the BB already has
783 // UnreachableInst at the end.
784 // This EmptyAsm is required to avoid callback merge.
785 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000786 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000787}
788
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000789Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000790 Value *ShadowValue,
791 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000792 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000793 // Addr & (Granularity - 1)
794 Value *LastAccessedByte = IRB.CreateAnd(
795 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
796 // (Addr & (Granularity - 1)) + size - 1
797 if (TypeSize / 8 > 1)
798 LastAccessedByte = IRB.CreateAdd(
799 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
800 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
801 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000802 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000803 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
804 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
805}
806
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000807void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Stephen Hinesdce4a402014-05-29 02:49:00 -0700808 Instruction *InsertBefore, Value *Addr,
809 uint32_t TypeSize, bool IsWrite,
810 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000811 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000812 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700813 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
814
815 if (UseCalls) {
816 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
817 AddrLong);
818 return;
819 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000820
821 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000822 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000823 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
824 Value *ShadowPtr = memToShadow(AddrLong, IRB);
825 Value *CmpVal = Constant::getNullValue(ShadowTy);
826 Value *ShadowValue = IRB.CreateLoad(
827 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
828
829 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000830 size_t Granularity = 1 << Mapping.Scale;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700831 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000832
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000833 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000834 TerminatorInst *CheckTerm =
Stephen Hines36b56882014-04-23 16:57:46 -0700835 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000836 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000837 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000838 IRB.SetInsertPoint(CheckTerm);
839 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000840 BasicBlock *CrashBlock =
841 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000842 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000843 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
844 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000845 } else {
Stephen Hines36b56882014-04-23 16:57:46 -0700846 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000847 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000848
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000849 Instruction *Crash = generateCrashCode(
850 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000851 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000852}
853
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000854void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000855 Module &M, GlobalValue *ModuleName) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700856 // We do all of our poisoning and unpoisoning within a global constructor.
857 // These are called _GLOBAL__(sub_)?I_.*.
858 // TODO: Consider looking through the functions in
859 // M.getGlobalVariable("llvm.global_ctors") instead of using this stringly
860 // typed approach.
861 Function *GlobalInit = nullptr;
862 for (auto &F : M.getFunctionList()) {
863 StringRef FName = F.getName();
864
865 const char kGlobalPrefix[] = "_GLOBAL__";
866 if (!FName.startswith(kGlobalPrefix))
867 continue;
868 FName = FName.substr(strlen(kGlobalPrefix));
869
870 const char kOptionalSub[] = "sub_";
871 if (FName.startswith(kOptionalSub))
872 FName = FName.substr(strlen(kOptionalSub));
873
874 if (FName.startswith("I_")) {
875 GlobalInit = &F;
876 break;
877 }
878 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000879 // If that function is not present, this TU contains no globals, or they have
880 // all been optimized away
881 if (!GlobalInit)
882 return;
883
884 // Set up the arguments to our poison/unpoison functions.
885 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
886
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000887 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000888 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
889 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000890
891 // Add calls to unpoison all globals before each return instruction.
892 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700893 I != E; ++I) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000894 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
895 CallInst::Create(AsanUnpoisonGlobals, "", RI);
896 }
897 }
898}
899
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000900bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000901 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000902 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000903
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000904 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000905 if (!Ty->isSized()) return false;
906 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000907 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000908 // Touch only those globals that will not be defined in other modules.
909 // Don't handle ODR type linkages since other modules may be built w/o asan.
910 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
911 G->getLinkage() != GlobalVariable::PrivateLinkage &&
912 G->getLinkage() != GlobalVariable::InternalLinkage)
913 return false;
914 // Two problems with thread-locals:
915 // - The address of the main thread's copy can't be computed at link-time.
916 // - Need to poison all copies, not just the main thread's one.
917 if (G->isThreadLocal())
918 return false;
Stephen Hines36b56882014-04-23 16:57:46 -0700919 // For now, just ignore this Global if the alignment is large.
920 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000921
922 // Ignore all the globals with the names starting with "\01L_OBJC_".
923 // Many of those are put into the .cstring section. The linker compresses
924 // that section by removing the spare \0s after the string terminator, so
925 // our redzones get broken.
926 if ((G->getName().find("\01L_OBJC_") == 0) ||
927 (G->getName().find("\01l_OBJC_") == 0)) {
Stephen Hines36b56882014-04-23 16:57:46 -0700928 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000929 return false;
930 }
931
932 if (G->hasSection()) {
933 StringRef Section(G->getSection());
934 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
935 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
936 // them.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700937 if (Section.startswith("__OBJC,") ||
938 Section.startswith("__DATA, __objc_")) {
Stephen Hines36b56882014-04-23 16:57:46 -0700939 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000940 return false;
941 }
942 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
943 // Constant CFString instances are compiled in the following way:
944 // -- the string buffer is emitted into
945 // __TEXT,__cstring,cstring_literals
946 // -- the constant NSConstantString structure referencing that buffer
947 // is placed into __DATA,__cfstring
948 // Therefore there's no point in placing redzones into __DATA,__cfstring.
949 // Moreover, it causes the linker to crash on OS X 10.7
Stephen Hinesdce4a402014-05-29 02:49:00 -0700950 if (Section.startswith("__DATA,__cfstring")) {
Stephen Hines36b56882014-04-23 16:57:46 -0700951 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000952 return false;
953 }
Stephen Hines36b56882014-04-23 16:57:46 -0700954 // The linker merges the contents of cstring_literals and removes the
955 // trailing zeroes.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700956 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
Stephen Hines36b56882014-04-23 16:57:46 -0700957 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
958 return false;
959 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700960
961 // Callbacks put into the CRT initializer/terminator sections
962 // should not be instrumented.
963 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
964 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
965 if (Section.startswith(".CRT")) {
966 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
967 return false;
968 }
969
Stephen Hines36b56882014-04-23 16:57:46 -0700970 // Globals from llvm.metadata aren't emitted, do not instrument them.
971 if (Section == "llvm.metadata") return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000972 }
973
974 return true;
975}
976
Alexey Samsonov46848582012-12-25 12:28:20 +0000977void AddressSanitizerModule::initializeCallbacks(Module &M) {
978 IRBuilder<> IRB(*C);
979 // Declare our poisoning and unpoisoning functions.
980 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000981 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000982 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
983 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
984 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
985 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
986 // Declare functions that register/unregister globals.
987 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
988 kAsanRegisterGlobalsName, IRB.getVoidTy(),
989 IntptrTy, IntptrTy, NULL));
990 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
991 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
992 kAsanUnregisterGlobalsName,
993 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
994 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700995 AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
996 kAsanCovModuleInitName,
997 IRB.getVoidTy(), IntptrTy, NULL));
998 AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
Alexey Samsonov46848582012-12-25 12:28:20 +0000999}
1000
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001001// This function replaces all global variables with new variables that have
1002// trailing redzones. It also creates a function that poisons
1003// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +00001004bool AddressSanitizerModule::runOnModule(Module &M) {
1005 if (!ClGlobals) return false;
Stephen Hines36b56882014-04-23 16:57:46 -07001006
1007 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1008 if (!DLP)
Kostya Serebryany1416edc2012-11-28 10:31:36 +00001009 return false;
Stephen Hines36b56882014-04-23 16:57:46 -07001010 DL = &DLP->getDataLayout();
1011
Alexey Samsonove39e1312013-08-12 11:46:09 +00001012 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +00001013 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001014 C = &(M.getContext());
Stephen Hines36b56882014-04-23 16:57:46 -07001015 int LongSize = DL->getPointerSizeInBits();
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001016 IntptrTy = Type::getIntNTy(*C, LongSize);
Stephen Hines36b56882014-04-23 16:57:46 -07001017 Mapping = getShadowMapping(M, LongSize);
Alexey Samsonov46848582012-12-25 12:28:20 +00001018 initializeCallbacks(M);
1019 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001020
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001021 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1022
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001023 for (Module::GlobalListType::iterator G = M.global_begin(),
1024 E = M.global_end(); G != E; ++G) {
1025 if (ShouldInstrumentGlobal(G))
1026 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001027 }
1028
Stephen Hinesdce4a402014-05-29 02:49:00 -07001029 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1030 assert(CtorFunc);
1031 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1032
1033 Function *CovFunc = M.getFunction(kAsanCovName);
1034 int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1035 IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1036
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001037 size_t n = GlobalsToChange.size();
1038 if (n == 0) return false;
1039
1040 // A global is described by a structure
1041 // size_t beg;
1042 // size_t size;
1043 // size_t size_with_redzone;
1044 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +00001045 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001046 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001047 // We initialize an array of such structures and pass it to a run-time call.
1048 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001049 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +00001050 IntptrTy, IntptrTy, NULL);
Rafael Espindola8819c842013-10-01 13:32:03 +00001051 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001052
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001053 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001054
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001055 // We shouldn't merge same module names, as this string serves as unique
1056 // module ID in runtime.
Stephen Hines36b56882014-04-23 16:57:46 -07001057 GlobalVariable *ModuleName = createPrivateGlobalForString(
1058 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryany086a4722013-03-18 08:05:29 +00001059
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001060 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +00001061 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001062 GlobalVariable *G = GlobalsToChange[i];
1063 PointerType *PtrTy = cast<PointerType>(G->getType());
1064 Type *Ty = PtrTy->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -07001065 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1066 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany63f08462013-01-24 10:35:40 +00001067 // MinRZ <= RZ <= kMaxGlobalRedzone
1068 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +00001069 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +00001070 std::min(kMaxGlobalRedzone,
1071 (SizeInBytes / MinRZ / 4) * MinRZ));
1072 uint64_t RightRedzoneSize = RZ;
1073 // Round up to MinRZ
1074 if (SizeInBytes % MinRZ)
1075 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1076 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001077 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001078 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +00001079 bool GlobalHasDynamicInitializer =
1080 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +00001081 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +00001082 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001083
1084 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1085 Constant *NewInitializer = ConstantStruct::get(
1086 NewTy, G->getInitializer(),
1087 Constant::getNullValue(RightRedZoneTy), NULL);
1088
Stephen Hines36b56882014-04-23 16:57:46 -07001089 GlobalVariable *Name =
1090 createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001091
1092 // Create a new global variable with enough space for a redzone.
Bill Wendling55a1a592013-08-06 22:52:42 +00001093 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1094 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1095 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001096 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001097 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001098 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001099 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +00001100 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001101
1102 Value *Indices2[2];
1103 Indices2[0] = IRB.getInt32(0);
1104 Indices2[1] = IRB.getInt32(0);
1105
1106 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +00001107 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001108 NewGlobal->takeName(G);
1109 G->eraseFromParent();
1110
1111 Initializers[i] = ConstantStruct::get(
1112 GlobalStructTy,
1113 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1114 ConstantInt::get(IntptrTy, SizeInBytes),
1115 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1116 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +00001117 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001118 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001119 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001120
1121 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001122 if (CheckInitOrder && GlobalHasDynamicInitializer)
1123 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001124
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001125 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001126 }
1127
1128 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1129 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001130 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001131 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1132
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001133 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001134 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1135 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001136 IRB.CreateCall2(AsanRegisterGlobals,
1137 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1138 ConstantInt::get(IntptrTy, n));
1139
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001140 // We also need to unregister globals at the end, e.g. when a shared library
1141 // gets closed.
1142 Function *AsanDtorFunction = Function::Create(
1143 FunctionType::get(Type::getVoidTy(*C), false),
1144 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1145 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1146 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001147 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1148 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1149 ConstantInt::get(IntptrTy, n));
1150 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1151
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001152 DEBUG(dbgs() << M);
1153 return true;
1154}
1155
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001156void AddressSanitizer::initializeCallbacks(Module &M) {
1157 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001158 // Create __asan_report* callbacks.
1159 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1160 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1161 AccessSizeIndex++) {
1162 // IsWrite and TypeSize are encoded in the function name.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001163 std::string Suffix =
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001164 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001165 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001166 checkInterfaceFunction(
1167 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1168 IRB.getVoidTy(), IntptrTy, NULL));
1169 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1170 checkInterfaceFunction(
1171 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1172 IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001173 }
1174 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001175 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1176 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1177 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1178 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001179
Stephen Hinesdce4a402014-05-29 02:49:00 -07001180 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1181 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1182 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1183 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1184 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1185 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1186
1187 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1188 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1189 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1190 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1191 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1192 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1193 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1194 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1195 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1196
1197 AsanHandleNoReturnFunc = checkInterfaceFunction(
1198 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Bob Wilson4b899142013-11-15 07:16:09 +00001199 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
Stephen Hines36b56882014-04-23 16:57:46 -07001200 kAsanCovName, IRB.getVoidTy(), NULL));
1201 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1202 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1203 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1204 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001205 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1206 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1207 StringRef(""), StringRef(""),
1208 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001209}
1210
1211// virtual
1212bool AddressSanitizer::doInitialization(Module &M) {
1213 // Initialize the private fields. No one has accessed them before.
Stephen Hines36b56882014-04-23 16:57:46 -07001214 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1215 if (!DLP)
Stephen Hinesdce4a402014-05-29 02:49:00 -07001216 report_fatal_error("data layout missing");
Stephen Hines36b56882014-04-23 16:57:46 -07001217 DL = &DLP->getDataLayout();
1218
Alexey Samsonove39e1312013-08-12 11:46:09 +00001219 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001220 DynamicallyInitializedGlobals.Init(M);
1221
1222 C = &(M.getContext());
Stephen Hines36b56882014-04-23 16:57:46 -07001223 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001224 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001225
1226 AsanCtorFunction = Function::Create(
1227 FunctionType::get(Type::getVoidTy(*C), false),
1228 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1229 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1230 // call __asan_init in the module ctor.
1231 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1232 AsanInitFunction = checkInterfaceFunction(
1233 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1234 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1235 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001236
Stephen Hines36b56882014-04-23 16:57:46 -07001237 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001238
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001239 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001240 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001241}
1242
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001243bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1244 // For each NSObject descendant having a +load method, this method is invoked
1245 // by the ObjC runtime before any of the static constructors is called.
1246 // Therefore we need to instrument such methods with a call to __asan_init
1247 // at the beginning in order to initialize our runtime before any access to
1248 // the shadow memory.
1249 // We cannot just ignore these methods, because they may call other
1250 // instrumented functions.
1251 if (F.getName().find(" load]") != std::string::npos) {
1252 IRBuilder<> IRB(F.begin()->begin());
1253 IRB.CreateCall(AsanInitFunction);
1254 return true;
1255 }
1256 return false;
1257}
1258
Stephen Hines36b56882014-04-23 16:57:46 -07001259void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1260 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1261 // Skip static allocas at the top of the entry block so they don't become
1262 // dynamic when we split the block. If we used our optimized stack layout,
1263 // then there will only be one alloca and it will come first.
1264 for (; IP != BE; ++IP) {
1265 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1266 if (!AI || !AI->isStaticAlloca())
1267 break;
1268 }
1269
1270 IRBuilder<> IRB(IP);
Bob Wilson4b899142013-11-15 07:16:09 +00001271 Type *Int8Ty = IRB.getInt8Ty();
1272 GlobalVariable *Guard = new GlobalVariable(
Kostya Serebryany8f15c682013-11-15 09:52:05 +00001273 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Bob Wilson4b899142013-11-15 07:16:09 +00001274 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1275 LoadInst *Load = IRB.CreateLoad(Guard);
1276 Load->setAtomic(Monotonic);
1277 Load->setAlignment(1);
1278 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
Stephen Hines36b56882014-04-23 16:57:46 -07001279 Instruction *Ins = SplitBlockAndInsertIfThen(
1280 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Bob Wilson4b899142013-11-15 07:16:09 +00001281 IRB.SetInsertPoint(Ins);
1282 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1283 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
Stephen Hines36b56882014-04-23 16:57:46 -07001284 Instruction *Call = IRB.CreateCall(AsanCovFunction);
1285 Call->setDebugLoc(IP->getDebugLoc());
Bob Wilson4b899142013-11-15 07:16:09 +00001286 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1287 Store->setAtomic(Monotonic);
1288 Store->setAlignment(1);
Stephen Hines36b56882014-04-23 16:57:46 -07001289}
1290
1291// Poor man's coverage that works with ASan.
1292// We create a Guard boolean variable with the same linkage
1293// as the function and inject this code into the entry block (-asan-coverage=1)
1294// or all blocks (-asan-coverage=2):
1295// if (*Guard) {
1296// __sanitizer_cov(&F);
1297// *Guard = 1;
1298// }
1299// The accesses to Guard are atomic. The rest of the logic is
1300// in __sanitizer_cov (it's fine to call it more than once).
1301//
1302// This coverage implementation provides very limited data:
1303// it only tells if a given function (block) was ever executed.
1304// No counters, no per-edge data.
1305// But for many use cases this is what we need and the added slowdown
1306// is negligible. This simple implementation will probably be obsoleted
1307// by the upcoming Clang-based coverage implementation.
1308// By having it here and now we hope to
1309// a) get the functionality to users earlier and
1310// b) collect usage statistics to help improve Clang coverage design.
1311bool AddressSanitizer::InjectCoverage(Function &F,
1312 const ArrayRef<BasicBlock *> AllBlocks) {
1313 if (!ClCoverage) return false;
1314
Stephen Hinesdce4a402014-05-29 02:49:00 -07001315 if (ClCoverage == 1 ||
1316 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001317 InjectCoverageAtBlock(F, F.getEntryBlock());
1318 } else {
1319 for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
1320 InjectCoverageAtBlock(F, *AllBlocks[i]);
1321 }
Bob Wilson4b899142013-11-15 07:16:09 +00001322 return true;
1323}
1324
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001325bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001326 if (BL->isIn(F)) return false;
1327 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001328 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001329 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001330 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001331
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001332 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001333 maybeInsertAsanInitAtFunctionEntry(F);
1334
Kostya Serebryany20985712013-06-26 09:18:17 +00001335 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001336 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001337
1338 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1339 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001340
1341 // We want to instrument every address only once per basic block (unless there
1342 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001343 SmallSet<Value*, 16> TempsToInstrument;
1344 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001345 SmallVector<Instruction*, 8> NoReturnCalls;
Stephen Hines36b56882014-04-23 16:57:46 -07001346 SmallVector<BasicBlock*, 16> AllBlocks;
1347 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany20985712013-06-26 09:18:17 +00001348 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001349 bool IsWrite;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001350 unsigned Alignment;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001351
1352 // Fill the set of memory operations to instrument.
1353 for (Function::iterator FI = F.begin(), FE = F.end();
1354 FI != FE; ++FI) {
Stephen Hines36b56882014-04-23 16:57:46 -07001355 AllBlocks.push_back(FI);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001356 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001357 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001358 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1359 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001360 if (LooksLikeCodeInBug11395(BI)) return false;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001361 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite, &Alignment)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001362 if (ClOpt && ClOptSameTemp) {
1363 if (!TempsToInstrument.insert(Addr))
1364 continue; // We've seen this temp in the current BB.
1365 }
Stephen Hines36b56882014-04-23 16:57:46 -07001366 } else if (ClInvalidPointerPairs &&
1367 isInterestingPointerComparisonOrSubtraction(BI)) {
1368 PointerComparisonsOrSubtracts.push_back(BI);
1369 continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001370 } else if (isa<MemIntrinsic>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001371 // ok, take it.
1372 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001373 if (isa<AllocaInst>(BI))
1374 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001375 CallSite CS(BI);
1376 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001377 // A call inside BB.
1378 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001379 if (CS.doesNotReturn())
1380 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001381 }
1382 continue;
1383 }
1384 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001385 NumInsnsPerBB++;
1386 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1387 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001388 }
1389 }
1390
Stephen Hinesdce4a402014-05-29 02:49:00 -07001391 Function *UninstrumentedDuplicate = nullptr;
Kostya Serebryany20985712013-06-26 09:18:17 +00001392 bool LikelyToInstrument =
1393 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1394 if (ClKeepUninstrumented && LikelyToInstrument) {
1395 ValueToValueMapTy VMap;
1396 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1397 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1398 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1399 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1400 }
1401
Stephen Hinesdce4a402014-05-29 02:49:00 -07001402 bool UseCalls = false;
1403 if (ClInstrumentationWithCallsThreshold >= 0 &&
1404 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1405 UseCalls = true;
1406
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001407 // Instrument.
1408 int NumInstrumented = 0;
1409 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1410 Instruction *Inst = ToInstrument[i];
1411 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1412 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001413 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1414 instrumentMop(Inst, UseCalls);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001415 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001416 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001417 }
1418 NumInstrumented++;
1419 }
1420
Alexey Samsonov59cca132012-12-25 12:04:36 +00001421 FunctionStackPoisoner FSP(F, *this);
1422 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001423
1424 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1425 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1426 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1427 Instruction *CI = NoReturnCalls[i];
1428 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001429 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001430 }
1431
Stephen Hines36b56882014-04-23 16:57:46 -07001432 for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
1433 instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
1434 NumInstrumented++;
1435 }
1436
Kostya Serebryany20985712013-06-26 09:18:17 +00001437 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilson4b899142013-11-15 07:16:09 +00001438
Stephen Hines36b56882014-04-23 16:57:46 -07001439 if (InjectCoverage(F, AllBlocks))
Bob Wilson4b899142013-11-15 07:16:09 +00001440 res = true;
1441
Kostya Serebryany20985712013-06-26 09:18:17 +00001442 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1443
1444 if (ClKeepUninstrumented) {
1445 if (!res) {
1446 // No instrumentation is done, no need for the duplicate.
1447 if (UninstrumentedDuplicate)
1448 UninstrumentedDuplicate->eraseFromParent();
1449 } else {
1450 // The function was instrumented. We must have the duplicate.
1451 assert(UninstrumentedDuplicate);
1452 UninstrumentedDuplicate->setSection("NOASAN");
1453 assert(!F.hasSection());
1454 F.setSection("ASAN");
1455 }
1456 }
1457
1458 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001459}
1460
Alexey Samsonov59cca132012-12-25 12:04:36 +00001461// Workaround for bug 11395: we don't want to instrument stack in functions
1462// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1463// FIXME: remove once the bug 11395 is fixed.
1464bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1465 if (LongSize != 32) return false;
1466 CallInst *CI = dyn_cast<CallInst>(I);
1467 if (!CI || !CI->isInlineAsm()) return false;
1468 if (CI->getNumArgOperands() <= 5) return false;
1469 // We have inline assembly with quite a few arguments.
1470 return true;
1471}
1472
1473void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1474 IRBuilder<> IRB(*C);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001475 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1476 std::string Suffix = itostr(i);
1477 AsanStackMallocFunc[i] = checkInterfaceFunction(
1478 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1479 IntptrTy, IntptrTy, NULL));
1480 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1481 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1482 IntptrTy, IntptrTy, NULL));
1483 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001484 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1485 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1486 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1487 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1488}
1489
Stephen Hines36b56882014-04-23 16:57:46 -07001490void
1491FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1492 IRBuilder<> &IRB, Value *ShadowBase,
1493 bool DoPoison) {
1494 size_t n = ShadowBytes.size();
1495 size_t i = 0;
1496 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1497 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1498 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1499 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1500 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1501 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1502 uint64_t Val = 0;
1503 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1504 if (ASan.DL->isLittleEndian())
1505 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1506 else
1507 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001508 }
Stephen Hines36b56882014-04-23 16:57:46 -07001509 if (!Val) continue;
1510 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1511 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1512 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1513 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001514 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001515 }
1516}
1517
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001518// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1519// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1520static int StackMallocSizeClass(uint64_t LocalStackSize) {
1521 assert(LocalStackSize <= kMaxStackMallocSize);
1522 uint64_t MaxSize = kMinStackMallocSize;
1523 for (int i = 0; ; i++, MaxSize *= 2)
1524 if (LocalStackSize <= MaxSize)
1525 return i;
1526 llvm_unreachable("impossible LocalStackSize");
1527}
1528
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001529// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1530// We can not use MemSet intrinsic because it may end up calling the actual
1531// memset. Size is a multiple of 8.
1532// Currently this generates 8-byte stores on x86_64; it may be better to
1533// generate wider stores.
1534void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1535 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1536 assert(!(Size % 8));
1537 assert(kAsanStackAfterReturnMagic == 0xf5);
1538 for (int i = 0; i < Size; i += 8) {
1539 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1540 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1541 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1542 }
1543}
1544
Stephen Hinesdce4a402014-05-29 02:49:00 -07001545static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1546 BasicBlock::iterator I = F.getEntryBlock().begin(),
1547 E = F.getEntryBlock().end();
1548 for (; I != E; ++I)
1549 if (!isa<AllocaInst>(I))
1550 break;
1551 return I->getDebugLoc();
1552}
1553
Alexey Samsonov59cca132012-12-25 12:04:36 +00001554void FunctionStackPoisoner::poisonStack() {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001555 int StackMallocIdx = -1;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001556 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001557
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001558 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001559 Instruction *InsBefore = AllocaVec[0];
1560 IRBuilder<> IRB(InsBefore);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001561 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001562
Stephen Hines36b56882014-04-23 16:57:46 -07001563 SmallVector<ASanStackVariableDescription, 16> SVD;
1564 SVD.reserve(AllocaVec.size());
1565 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1566 AllocaInst *AI = AllocaVec[i];
1567 ASanStackVariableDescription D = { AI->getName().data(),
1568 getAllocaSizeInBytes(AI),
1569 AI->getAlignment(), AI, 0};
1570 SVD.push_back(D);
1571 }
1572 // Minimal header size (left redzone) is 4 pointers,
1573 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1574 size_t MinHeaderSize = ASan.LongSize / 2;
1575 ASanStackFrameLayout L;
1576 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1577 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1578 uint64_t LocalStackSize = L.FrameSize;
1579 bool DoStackMalloc =
1580 ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001581
1582 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1583 AllocaInst *MyAlloca =
1584 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001585 MyAlloca->setDebugLoc(EntryDebugLocation);
Stephen Hines36b56882014-04-23 16:57:46 -07001586 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1587 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1588 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001589 assert(MyAlloca->isStaticAlloca());
1590 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1591 Value *LocalStackBase = OrigStackBase;
1592
1593 if (DoStackMalloc) {
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001594 // LocalStackBase = OrigStackBase
1595 // if (__asan_option_detect_stack_use_after_return)
1596 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001597 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1598 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001599 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1600 kAsanOptionDetectUAR, IRB.getInt32Ty());
1601 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1602 Constant::getNullValue(IRB.getInt32Ty()));
Stephen Hines36b56882014-04-23 16:57:46 -07001603 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001604 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1605 IRBuilder<> IRBIf(Term);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001606 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001607 LocalStackBase = IRBIf.CreateCall2(
1608 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001609 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001610 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1611 IRB.SetInsertPoint(InsBefore);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001612 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001613 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1614 Phi->addIncoming(OrigStackBase, CmpBlock);
1615 Phi->addIncoming(LocalStackBase, SetBlock);
1616 LocalStackBase = Phi;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001617 }
1618
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001619 // Insert poison calls for lifetime intrinsics for alloca.
1620 bool HavePoisonedAllocas = false;
1621 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1622 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
Alexey Samsonov64409ad2013-11-18 14:53:55 +00001623 assert(APC.InsBefore);
1624 assert(APC.AI);
1625 IRBuilder<> IRB(APC.InsBefore);
1626 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001627 HavePoisonedAllocas |= APC.DoPoison;
1628 }
1629
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001630 // Replace Alloca instructions with base+offset.
Stephen Hines36b56882014-04-23 16:57:46 -07001631 for (size_t i = 0, n = SVD.size(); i < n; i++) {
1632 AllocaInst *AI = SVD[i].AI;
Alexey Samsonovf985f442012-12-04 01:34:23 +00001633 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Stephen Hines36b56882014-04-23 16:57:46 -07001634 IRB.CreateAdd(LocalStackBase,
1635 ConstantInt::get(IntptrTy, SVD[i].Offset)),
1636 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001637 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001638 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001639 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001640
Kostya Serebryany30160562013-03-22 10:37:20 +00001641 // The left-most redzone has enough space for at least 4 pointers.
1642 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001643 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1644 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1645 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001646 // Write the frame description constant to redzone[1].
1647 Value *BasePlus1 = IRB.CreateIntToPtr(
1648 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1649 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001650 GlobalVariable *StackDescriptionGlobal =
Stephen Hines36b56882014-04-23 16:57:46 -07001651 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1652 /*AllowMerging*/true);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001653 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1654 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001655 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001656 // Write the PC to redzone[2].
1657 Value *BasePlus2 = IRB.CreateIntToPtr(
1658 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1659 2 * ASan.LongSize/8)),
1660 IntptrPtrTy);
1661 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001662
1663 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001664 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Stephen Hines36b56882014-04-23 16:57:46 -07001665 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001666
Stephen Hines36b56882014-04-23 16:57:46 -07001667 // (Un)poison the stack before all ret instructions.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001668 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1669 Instruction *Ret = RetVec[i];
1670 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001671 // Mark the current frame as retired.
1672 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1673 BasePlus0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001674 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001675 assert(StackMallocIdx >= 0);
Stephen Hines36b56882014-04-23 16:57:46 -07001676 // if LocalStackBase != OrigStackBase:
1677 // // In use-after-return mode, poison the whole stack frame.
1678 // if StackMallocIdx <= 4
1679 // // For small sizes inline the whole thing:
1680 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1681 // **SavedFlagPtr(LocalStackBase) = 0
1682 // else
1683 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1684 // else
1685 // <This is not a fake stack; unpoison the redzones>
1686 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1687 TerminatorInst *ThenTerm, *ElseTerm;
1688 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1689
1690 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001691 if (StackMallocIdx <= 4) {
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001692 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1693 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1694 ClassSize >> Mapping.Scale);
1695 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1696 LocalStackBase,
1697 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1698 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1699 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1700 IRBPoison.CreateStore(
1701 Constant::getNullValue(IRBPoison.getInt8Ty()),
1702 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1703 } else {
1704 // For larger frames call __asan_stack_free_*.
Stephen Hines36b56882014-04-23 16:57:46 -07001705 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1706 ConstantInt::get(IntptrTy, LocalStackSize),
1707 OrigStackBase);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001708 }
Stephen Hines36b56882014-04-23 16:57:46 -07001709
1710 IRBuilder<> IRBElse(ElseTerm);
1711 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001712 } else if (HavePoisonedAllocas) {
1713 // If we poisoned some allocas in llvm.lifetime analysis,
1714 // unpoison whole stack frame now.
1715 assert(LocalStackBase == OrigStackBase);
1716 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Stephen Hines36b56882014-04-23 16:57:46 -07001717 } else {
1718 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001719 }
1720 }
1721
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001722 // We are done. Remove the old unused alloca instructions.
1723 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1724 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001725}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001726
Alexey Samsonov59cca132012-12-25 12:04:36 +00001727void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak4c710642013-08-09 20:53:48 +00001728 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001729 // For now just insert the call to ASan runtime.
1730 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1731 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1732 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1733 : AsanUnpoisonStackMemoryFunc,
1734 AddrArg, SizeArg);
1735}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001736
1737// Handling llvm.lifetime intrinsics for a given %alloca:
1738// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1739// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1740// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1741// could be poisoned by previous llvm.lifetime.end instruction, as the
1742// variable may go in and out of scope several times, e.g. in loops).
1743// (3) if we poisoned at least one %alloca in a function,
1744// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001745
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001746AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1747 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1748 // We're intested only in allocas we can handle.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001749 return isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001750 // See if we've already calculated (or started to calculate) alloca for a
1751 // given value.
1752 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1753 if (I != AllocaForValue.end())
1754 return I->second;
1755 // Store 0 while we're calculating alloca for value V to avoid
1756 // infinite recursion if the value references itself.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001757 AllocaForValue[V] = nullptr;
1758 AllocaInst *Res = nullptr;
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001759 if (CastInst *CI = dyn_cast<CastInst>(V))
1760 Res = findAllocaForValue(CI->getOperand(0));
1761 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1763 Value *IncValue = PN->getIncomingValue(i);
1764 // Allow self-referencing phi-nodes.
1765 if (IncValue == PN) continue;
1766 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1767 // AI for incoming values should exist and should all be equal.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001768 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1769 return nullptr;
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001770 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001771 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001772 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001773 if (Res)
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001774 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001775 return Res;
1776}