blob: d731ec5499eae35f426d155a64cab5fa2bc0f532 [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
16#define DEBUG_TYPE "asan"
17
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000020#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000021#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000022#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
Kostya Serebryany3386d252013-10-16 14:06:14 +000026#include "llvm/ADT/Statistic.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000027#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000028#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000029#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000038#include "llvm/InstVisitor.h"
Kostya Serebryany1479c9b2013-02-20 12:35:15 +000039#include "llvm/Support/CallSite.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000040#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/DataTypes.h"
42#include "llvm/Support/Debug.h"
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000043#include "llvm/Support/Endian.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Support/raw_ostream.h"
45#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany20985712013-06-26 09:18:17 +000047#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000048#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000049#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne405515d2013-07-09 22:02:49 +000050#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000051#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000052#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000053
54using namespace llvm;
55
56static const uint64_t kDefaultShadowScale = 3;
57static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryany117de482013-02-11 14:36:01 +000059static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000060static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000061static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000062
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000063static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany800e03f2011-11-16 01:35:23 +000064static const size_t kMaxStackMallocSize = 1 << 16; // 64K
65static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
66static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
67
Craig Topper4172a8a2013-07-16 01:17:10 +000068static const char *const kAsanModuleCtorName = "asan.module_ctor";
69static const char *const kAsanModuleDtorName = "asan.module_dtor";
70static const int kAsanCtorAndCtorPriority = 1;
71static const char *const kAsanReportErrorTemplate = "__asan_report_";
72static const char *const kAsanReportLoadN = "__asan_report_load_n";
73static const char *const kAsanReportStoreN = "__asan_report_store_n";
74static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonov48d7d1d2013-08-05 13:19:49 +000075static const char *const kAsanUnregisterGlobalsName =
76 "__asan_unregister_globals";
Craig Topper4172a8a2013-07-16 01:17:10 +000077static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
78static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
79static const char *const kAsanInitName = "__asan_init_v3";
Bob Wilson4b899142013-11-15 07:16:09 +000080static const char *const kAsanCovName = "__sanitizer_cov";
Craig Topper4172a8a2013-07-16 01:17:10 +000081static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
82static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
83static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000084static const int kMaxAsanStackMallocSizeClass = 10;
85static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
86static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topper4172a8a2013-07-16 01:17:10 +000087static const char *const kAsanGenPrefix = "__asan_gen_";
88static const char *const kAsanPoisonStackMemoryName =
89 "__asan_poison_stack_memory";
90static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonovf985f442012-12-04 01:34:23 +000091 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000092
Kostya Serebryanyac04aba2013-09-18 14:07:14 +000093static const char *const kAsanOptionDetectUAR =
94 "__asan_option_detect_stack_use_after_return";
95
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000096// These constants must match the definitions in the run-time library.
Kostya Serebryany800e03f2011-11-16 01:35:23 +000097static const int kAsanStackLeftRedzoneMagic = 0xf1;
98static const int kAsanStackMidRedzoneMagic = 0xf2;
99static const int kAsanStackRightRedzoneMagic = 0xf3;
100static const int kAsanStackPartialRedzoneMagic = 0xf4;
David Blaikie0b956502013-09-18 00:11:27 +0000101#ifndef NDEBUG
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000102static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikie0b956502013-09-18 00:11:27 +0000103#endif
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000104
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000105// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
106static const size_t kNumberOfAccessSizes = 5;
107
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000108// Command-line flags.
109
110// This flag may need to be replaced with -f[no-]asan-reads.
111static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
112 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
113static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
114 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000115static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
116 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
117 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000118static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
119 cl::desc("use instrumentation with slow path for all accesses"),
120 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000121// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000122// in any given BB. Normally, this should be set to unlimited (INT_MAX),
123// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
124// set it to 10000.
125static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
126 cl::init(10000),
127 cl::desc("maximal number of instructions to instrument in any given BB"),
128 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000129// This flag may need to be replaced with -f[no]asan-stack.
130static cl::opt<bool> ClStack("asan-stack",
131 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
132// This flag may need to be replaced with -f[no]asan-use-after-return.
133static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
134 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
135// This flag may need to be replaced with -f[no]asan-globals.
136static cl::opt<bool> ClGlobals("asan-globals",
137 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Bob Wilson4b899142013-11-15 07:16:09 +0000138static cl::opt<bool> ClCoverage("asan-coverage",
139 cl::desc("ASan coverage"), cl::Hidden, cl::init(false));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000140static cl::opt<bool> ClInitializers("asan-initialization-order",
141 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000142static cl::opt<bool> ClMemIntrin("asan-memintrin",
143 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000144static cl::opt<bool> ClRealignStack("asan-realign-stack",
145 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000146static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
147 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000148 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000149
Kostya Serebryany20985712013-06-26 09:18:17 +0000150// This is an experimental feature that will allow to choose between
151// instrumented and non-instrumented code at link-time.
152// If this option is on, just before instrumenting a function we create its
153// clone; if the function is not changed by asan the clone is deleted.
154// If we end up with a clone, we put the instrumented function into a section
155// called "ASAN" and the uninstrumented function into a section called "NOASAN".
156//
157// This is still a prototype, we need to figure out a way to keep two copies of
158// a function so that the linker can easily choose one of them.
159static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
160 cl::desc("Keep uninstrumented copies of functions"),
161 cl::Hidden, cl::init(false));
162
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000163// These flags allow to change the shadow mapping.
164// The shadow mapping looks like
165// Shadow = (Mem >> scale) + (1 << offset_log)
166static cl::opt<int> ClMappingScale("asan-mapping-scale",
167 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
168static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
169 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000170static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
171 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000172 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000173
174// Optimization flags. Not user visible, used mostly for testing
175// and benchmarking the tool.
176static cl::opt<bool> ClOpt("asan-opt",
177 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
178static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
179 cl::desc("Instrument the same temp just once"), cl::Hidden,
180 cl::init(true));
181static cl::opt<bool> ClOptGlobals("asan-opt-globals",
182 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
183
Alexey Samsonovee548272012-11-29 18:14:24 +0000184static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
185 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
186 cl::Hidden, cl::init(false));
187
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000188// Debug flags.
189static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
190 cl::init(0));
191static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
192 cl::Hidden, cl::init(0));
193static cl::opt<std::string> ClDebugFunc("asan-debug-func",
194 cl::Hidden, cl::desc("Debug func"));
195static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
196 cl::Hidden, cl::init(-1));
197static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
198 cl::Hidden, cl::init(-1));
199
Kostya Serebryany3386d252013-10-16 14:06:14 +0000200STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
201STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
202STATISTIC(NumOptimizedAccessesToGlobalArray,
203 "Number of optimized accesses to global arrays");
204STATISTIC(NumOptimizedAccessesToGlobalVar,
205 "Number of optimized accesses to global vars");
206
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000207namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000208/// A set of dynamically initialized globals extracted from metadata.
209class SetOfDynamicallyInitializedGlobals {
210 public:
211 void Init(Module& M) {
212 // Clang generates metadata identifying all dynamically initialized globals.
213 NamedMDNode *DynamicGlobals =
214 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
215 if (!DynamicGlobals)
216 return;
217 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
218 MDNode *MDN = DynamicGlobals->getOperand(i);
219 assert(MDN->getNumOperands() == 1);
220 Value *VG = MDN->getOperand(0);
221 // The optimizer may optimize away a global entirely, in which case we
222 // cannot instrument access to it.
223 if (!VG)
224 continue;
225 DynInitGlobals.insert(cast<GlobalVariable>(VG));
226 }
227 }
228 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
229 private:
230 SmallSet<GlobalValue*, 32> DynInitGlobals;
231};
232
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000233/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000234/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000235struct ShadowMapping {
236 int Scale;
237 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000238 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000239};
240
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000241static ShadowMapping getShadowMapping(const Module &M, int LongSize,
242 bool ZeroBaseShadow) {
243 llvm::Triple TargetTriple(M.getTargetTriple());
244 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000245 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000246 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
247 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000248 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000249 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
250 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000251
252 ShadowMapping Mapping;
253
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000254 // OR-ing shadow offset if more efficient (at least on x86),
255 // but on ppc64 we have to use add since the shadow offset is not neccesary
256 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000257 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000258
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000259 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000260 (LongSize == 32 ?
261 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000262 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000263 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000264 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000265 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000266 }
267 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000268 // Zero offset log is the special case.
269 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
270 }
271
272 Mapping.Scale = kDefaultShadowScale;
273 if (ClMappingScale) {
274 Mapping.Scale = ClMappingScale;
275 }
276
277 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000278}
279
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000280static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000281 // Redzone used for stack and globals is at least 32 bytes.
282 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000283 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000284}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000285
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000286/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000287struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000288 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000289 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000290 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000291 StringRef BlacklistFile = StringRef(),
292 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000293 : FunctionPass(ID),
294 CheckInitOrder(CheckInitOrder || ClInitializers),
295 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000296 CheckLifetime(CheckLifetime || ClCheckLifetime),
297 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000298 : BlacklistFile),
299 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000300 virtual const char *getPassName() const {
301 return "AddressSanitizerFunctionPass";
302 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000303 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000304 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
305 Value *Addr, uint32_t TypeSize, bool IsWrite,
306 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000307 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
308 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000309 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000310 bool IsWrite, size_t AccessSizeIndex,
311 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000312 bool instrumentMemIntrinsic(MemIntrinsic *MI);
313 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000314 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000315 Instruction *InsertBefore, bool IsWrite);
316 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000317 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000318 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000319 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000320 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000321 static char ID; // Pass identification, replacement for typeid
322
323 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000324 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000326 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000327 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000328 void FindDynamicInitializers(Module &M);
Kostya Serebryany3386d252013-10-16 14:06:14 +0000329 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Bob Wilson4b899142013-11-15 07:16:09 +0000330 bool InjectCoverage(Function &F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000331
Alexey Samsonovee548272012-11-29 18:14:24 +0000332 bool CheckInitOrder;
333 bool CheckUseAfterReturn;
334 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000335 SmallString<64> BlacklistFile;
336 bool ZeroBaseShadow;
337
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000338 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000339 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000340 int LongSize;
341 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000342 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000343 Function *AsanCtorFunction;
344 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000345 Function *AsanHandleNoReturnFunc;
Bob Wilson4b899142013-11-15 07:16:09 +0000346 Function *AsanCovFunction;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000347 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000348 // This array is indexed by AccessIsWrite and log2(AccessSize).
349 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000350 // This array is indexed by AccessIsWrite.
351 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000352 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000353 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000354
355 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000356};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000357
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000358class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000359 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000360 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000361 StringRef BlacklistFile = StringRef(),
362 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000363 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000364 CheckInitOrder(CheckInitOrder || ClInitializers),
365 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000366 : BlacklistFile),
367 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000368 bool runOnModule(Module &M);
369 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000370 virtual const char *getPassName() const {
371 return "AddressSanitizerModule";
372 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000373
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000374 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000375 void initializeCallbacks(Module &M);
376
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000377 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000378 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000379 size_t RedzoneSize() const {
380 return RedzoneSizeForScale(Mapping.Scale);
381 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000382
Alexey Samsonovee548272012-11-29 18:14:24 +0000383 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000384 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000385 bool ZeroBaseShadow;
386
Peter Collingbourne405515d2013-07-09 22:02:49 +0000387 OwningPtr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000388 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
389 Type *IntptrTy;
390 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000391 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000392 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000393 Function *AsanPoisonGlobals;
394 Function *AsanUnpoisonGlobals;
395 Function *AsanRegisterGlobals;
396 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000397};
398
Alexey Samsonov59cca132012-12-25 12:04:36 +0000399// Stack poisoning does not play well with exception handling.
400// When an exception is thrown, we essentially bypass the code
401// that unpoisones the stack. This is why the run-time library has
402// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
403// stack in the interceptor. This however does not work inside the
404// actual function which catches the exception. Most likely because the
405// compiler hoists the load of the shadow value somewhere too high.
406// This causes asan to report a non-existing bug on 453.povray.
407// It sounds like an LLVM bug.
408struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
409 Function &F;
410 AddressSanitizer &ASan;
411 DIBuilder DIB;
412 LLVMContext *C;
413 Type *IntptrTy;
414 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000415 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000416
417 SmallVector<AllocaInst*, 16> AllocaVec;
418 SmallVector<Instruction*, 8> RetVec;
419 uint64_t TotalStackSize;
420 unsigned StackAlignment;
421
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +0000422 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
423 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov59cca132012-12-25 12:04:36 +0000424 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
425
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000426 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
427 struct AllocaPoisonCall {
428 IntrinsicInst *InsBefore;
Alexey Samsonov64409ad2013-11-18 14:53:55 +0000429 AllocaInst *AI;
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000430 uint64_t Size;
431 bool DoPoison;
432 };
433 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
434
435 // Maps Value to an AllocaInst from which the Value is originated.
436 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
437 AllocaForValueMapTy AllocaForValue;
438
Alexey Samsonov59cca132012-12-25 12:04:36 +0000439 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
440 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
441 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000442 Mapping(ASan.Mapping),
443 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000444
445 bool runOnFunction() {
446 if (!ClStack) return false;
447 // Collect alloca, ret, lifetime instructions etc.
448 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
449 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
450 BasicBlock *BB = *DI;
451 visit(*BB);
452 }
453 if (AllocaVec.empty()) return false;
454
455 initializeCallbacks(*F.getParent());
456
457 poisonStack();
458
459 if (ClDebugStack) {
460 DEBUG(dbgs() << F);
461 }
462 return true;
463 }
464
465 // Finds all static Alloca instructions and puts
466 // poisoned red zones around all of them.
467 // Then unpoison everything back before the function returns.
468 void poisonStack();
469
470 // ----------------------- Visitors.
471 /// \brief Collect all Ret instructions.
472 void visitReturnInst(ReturnInst &RI) {
473 RetVec.push_back(&RI);
474 }
475
476 /// \brief Collect Alloca instructions we want (and can) handle.
477 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000478 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000479
480 StackAlignment = std::max(StackAlignment, AI.getAlignment());
481 AllocaVec.push_back(&AI);
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000482 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000483 TotalStackSize += AlignedSize;
484 }
485
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000486 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
487 /// errors.
488 void visitIntrinsicInst(IntrinsicInst &II) {
489 if (!ASan.CheckLifetime) return;
490 Intrinsic::ID ID = II.getIntrinsicID();
491 if (ID != Intrinsic::lifetime_start &&
492 ID != Intrinsic::lifetime_end)
493 return;
494 // Found lifetime intrinsic, add ASan instrumentation if necessary.
495 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
496 // If size argument is undefined, don't do anything.
497 if (Size->isMinusOne()) return;
498 // Check that size doesn't saturate uint64_t and can
499 // be stored in IntptrTy.
500 const uint64_t SizeValue = Size->getValue().getLimitedValue();
501 if (SizeValue == ~0ULL ||
502 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
503 return;
504 // Find alloca instruction that corresponds to llvm.lifetime argument.
505 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
506 if (!AI) return;
507 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonov64409ad2013-11-18 14:53:55 +0000508 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000509 AllocaPoisonCallVec.push_back(APC);
510 }
511
Alexey Samsonov59cca132012-12-25 12:04:36 +0000512 // ---------------------- Helpers.
513 void initializeCallbacks(Module &M);
514
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000515 // Check if we want (and can) handle this alloca.
Jakub Staszak4c710642013-08-09 20:53:48 +0000516 bool isInterestingAlloca(AllocaInst &AI) const {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000517 return (!AI.isArrayAllocation() &&
518 AI.isStaticAlloca() &&
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000519 AI.getAlignment() <= RedzoneSize() &&
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000520 AI.getAllocatedType()->isSized());
521 }
522
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000523 size_t RedzoneSize() const {
524 return RedzoneSizeForScale(Mapping.Scale);
525 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000526 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000527 Type *Ty = AI->getAllocatedType();
528 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
529 return SizeInBytes;
530 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000531 uint64_t getAlignedSize(uint64_t SizeInBytes) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000532 size_t RZ = RedzoneSize();
533 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
534 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000535 uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000536 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
537 return getAlignedSize(SizeInBytes);
538 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000539 /// Finds alloca where the value comes from.
540 AllocaInst *findAllocaForValue(Value *V);
Jakub Staszak4c710642013-08-09 20:53:48 +0000541 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, 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,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000557 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000558 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000559 CheckLifetime, BlacklistFile, ZeroBaseShadow);
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(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000567 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
568 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
569 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000570}
571
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000572static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000573 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000574 assert(Res < kNumberOfAccessSizes);
575 return Res;
576}
577
Bill Wendling55a1a592013-08-06 22:52:42 +0000578// \brief Create a constant for Str so that we can pass it to the run-time lib.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000580 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000581 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Bill Wendling55a1a592013-08-06 22:52:42 +0000582 GlobalValue::InternalLinkage, StrConst,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000583 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000584 GV->setUnnamedAddr(true); // Ok to merge these.
585 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
586 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000587}
588
589static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
590 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000591}
592
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
594 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000595 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
596 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000597 return Shadow;
598 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000599 if (Mapping.OrShadowOffset)
600 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
601 else
602 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000603}
604
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000605void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000606 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000607 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000608 IRBuilder<> IRB(InsertBefore);
609 if (Size->getType() != IntptrTy)
610 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000611 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000612 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000613 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000614 IRB.SetInsertPoint(InsertBefore);
615 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
616 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
617 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
618 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000619}
620
621// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000622bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000623 Value *Dst = MI->getDest();
624 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000625 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000626 Value *Length = MI->getLength();
627
628 Constant *ConstLength = dyn_cast<Constant>(Length);
629 Instruction *InsertBefore = MI;
630 if (ConstLength) {
631 if (ConstLength->isNullValue()) return false;
632 } else {
633 // The size is not a constant so it could be zero -- check at run-time.
634 IRBuilder<> IRB(InsertBefore);
635
636 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000637 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000638 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000639 }
640
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000641 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000643 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000644 return true;
645}
646
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000647// If I is an interesting memory access, return the PointerOperand
648// and set IsWrite. Otherwise return NULL.
649static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000650 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000651 if (!ClInstrumentReads) return NULL;
652 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000653 return LI->getPointerOperand();
654 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000655 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
656 if (!ClInstrumentWrites) return NULL;
657 *IsWrite = true;
658 return SI->getPointerOperand();
659 }
660 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
661 if (!ClInstrumentAtomics) return NULL;
662 *IsWrite = true;
663 return RMW->getPointerOperand();
664 }
665 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
666 if (!ClInstrumentAtomics) return NULL;
667 *IsWrite = true;
668 return XCHG->getPointerOperand();
669 }
670 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000671}
672
Kostya Serebryany3386d252013-10-16 14:06:14 +0000673bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
674 // If a global variable does not have dynamic initialization we don't
675 // have to instrument it. However, if a global does not have initializer
676 // at all, we assume it has dynamic initializer (in other TU).
677 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
678}
679
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000680void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000681 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000682 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
683 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000684 if (ClOpt && ClOptGlobals) {
685 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
686 // If initialization order checking is disabled, a simple access to a
687 // dynamically initialized global is always valid.
Kostya Serebryany3386d252013-10-16 14:06:14 +0000688 if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
689 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000690 return;
Kostya Serebryany3386d252013-10-16 14:06:14 +0000691 }
692 }
693 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
694 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
695 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
696 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
697 NumOptimizedAccessesToGlobalArray++;
698 return;
699 }
700 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000701 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000702 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000703
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000704 Type *OrigPtrTy = Addr->getType();
705 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
706
707 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000708 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000709
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000710 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000711
Kostya Serebryany3386d252013-10-16 14:06:14 +0000712 if (IsWrite)
713 NumInstrumentedWrites++;
714 else
715 NumInstrumentedReads++;
716
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000717 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
718 if (TypeSize == 8 || TypeSize == 16 ||
719 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
720 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
721 // Instrument unusual size (but still multiple of 8).
722 // We can not do it with a single check, so we do 1-byte check for the first
723 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
724 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000725 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000726 Value *LastByte = IRB.CreateIntToPtr(
727 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
728 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
729 OrigPtrTy);
730 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
731 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
732 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000733}
734
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000735// Validate the result of Module::getOrInsertFunction called for an interface
736// function of AddressSanitizer. If the instrumented module defines a function
737// with the same name, their prototypes must match, otherwise
738// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000739static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000740 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
741 FuncOrBitcast->dump();
742 report_fatal_error("trying to redefine an AddressSanitizer "
743 "interface function");
744}
745
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000746Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000747 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000748 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000749 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000750 CallInst *Call = SizeArgument
751 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
752 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
753
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000754 // We don't do Call->setDoesNotReturn() because the BB already has
755 // UnreachableInst at the end.
756 // This EmptyAsm is required to avoid callback merge.
757 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000758 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000759}
760
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000761Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000762 Value *ShadowValue,
763 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000764 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000765 // Addr & (Granularity - 1)
766 Value *LastAccessedByte = IRB.CreateAnd(
767 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
768 // (Addr & (Granularity - 1)) + size - 1
769 if (TypeSize / 8 > 1)
770 LastAccessedByte = IRB.CreateAdd(
771 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
772 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
773 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000774 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000775 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
776 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
777}
778
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000779void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000780 Instruction *InsertBefore,
781 Value *Addr, uint32_t TypeSize,
782 bool IsWrite, Value *SizeArgument) {
783 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000784 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
785
786 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000787 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000788 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
789 Value *ShadowPtr = memToShadow(AddrLong, IRB);
790 Value *CmpVal = Constant::getNullValue(ShadowTy);
791 Value *ShadowValue = IRB.CreateLoad(
792 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
793
794 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000795 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000796 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000797 TerminatorInst *CrashTerm = 0;
798
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000799 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000800 TerminatorInst *CheckTerm =
801 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000802 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000803 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000804 IRB.SetInsertPoint(CheckTerm);
805 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000806 BasicBlock *CrashBlock =
807 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000808 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000809 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
810 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000811 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000812 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000813 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000814
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000815 Instruction *Crash = generateCrashCode(
816 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000817 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000818}
819
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000820void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000821 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000822 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
823 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
824 // If that function is not present, this TU contains no globals, or they have
825 // all been optimized away
826 if (!GlobalInit)
827 return;
828
829 // Set up the arguments to our poison/unpoison functions.
830 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
831
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000832 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000833 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
834 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000835
836 // Add calls to unpoison all globals before each return instruction.
837 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
838 I != E; ++I) {
839 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
840 CallInst::Create(AsanUnpoisonGlobals, "", RI);
841 }
842 }
843}
844
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000845bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000846 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000847 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000848
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000849 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000850 if (!Ty->isSized()) return false;
851 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000852 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000853 // Touch only those globals that will not be defined in other modules.
854 // Don't handle ODR type linkages since other modules may be built w/o asan.
855 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
856 G->getLinkage() != GlobalVariable::PrivateLinkage &&
857 G->getLinkage() != GlobalVariable::InternalLinkage)
858 return false;
859 // Two problems with thread-locals:
860 // - The address of the main thread's copy can't be computed at link-time.
861 // - Need to poison all copies, not just the main thread's one.
862 if (G->isThreadLocal())
863 return false;
864 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000865 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000866
867 // Ignore all the globals with the names starting with "\01L_OBJC_".
868 // Many of those are put into the .cstring section. The linker compresses
869 // that section by removing the spare \0s after the string terminator, so
870 // our redzones get broken.
871 if ((G->getName().find("\01L_OBJC_") == 0) ||
872 (G->getName().find("\01l_OBJC_") == 0)) {
873 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
874 return false;
875 }
876
877 if (G->hasSection()) {
878 StringRef Section(G->getSection());
879 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
880 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
881 // them.
882 if ((Section.find("__OBJC,") == 0) ||
883 (Section.find("__DATA, __objc_") == 0)) {
884 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
885 return false;
886 }
887 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
888 // Constant CFString instances are compiled in the following way:
889 // -- the string buffer is emitted into
890 // __TEXT,__cstring,cstring_literals
891 // -- the constant NSConstantString structure referencing that buffer
892 // is placed into __DATA,__cfstring
893 // Therefore there's no point in placing redzones into __DATA,__cfstring.
894 // Moreover, it causes the linker to crash on OS X 10.7
895 if (Section.find("__DATA,__cfstring") == 0) {
896 DEBUG(dbgs() << "Ignoring CFString: " << *G);
897 return false;
898 }
899 }
900
901 return true;
902}
903
Alexey Samsonov46848582012-12-25 12:28:20 +0000904void AddressSanitizerModule::initializeCallbacks(Module &M) {
905 IRBuilder<> IRB(*C);
906 // Declare our poisoning and unpoisoning functions.
907 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000908 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000909 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
910 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
911 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
912 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
913 // Declare functions that register/unregister globals.
914 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
915 kAsanRegisterGlobalsName, IRB.getVoidTy(),
916 IntptrTy, IntptrTy, NULL));
917 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
918 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
919 kAsanUnregisterGlobalsName,
920 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
921 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
922}
923
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000924// This function replaces all global variables with new variables that have
925// trailing redzones. It also creates a function that poisons
926// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000927bool AddressSanitizerModule::runOnModule(Module &M) {
928 if (!ClGlobals) return false;
929 TD = getAnalysisIfAvailable<DataLayout>();
930 if (!TD)
931 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +0000932 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000933 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000934 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000935 int LongSize = TD->getPointerSizeInBits();
936 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000937 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000938 initializeCallbacks(M);
939 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000940
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000941 SmallVector<GlobalVariable *, 16> GlobalsToChange;
942
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000943 for (Module::GlobalListType::iterator G = M.global_begin(),
944 E = M.global_end(); G != E; ++G) {
945 if (ShouldInstrumentGlobal(G))
946 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000947 }
948
949 size_t n = GlobalsToChange.size();
950 if (n == 0) return false;
951
952 // A global is described by a structure
953 // size_t beg;
954 // size_t size;
955 // size_t size_with_redzone;
956 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000957 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000958 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000959 // We initialize an array of such structures and pass it to a run-time call.
960 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000961 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000962 IntptrTy, IntptrTy, NULL);
Rafael Espindola8819c842013-10-01 13:32:03 +0000963 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000964
965 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
966 assert(CtorFunc);
967 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000968
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000969 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000970
Kostya Serebryany086a4722013-03-18 08:05:29 +0000971 GlobalVariable *ModuleName = createPrivateGlobalForString(
972 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000973 // We shouldn't merge same module names, as this string serves as unique
974 // module ID in runtime.
975 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000976
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000977 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000978 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000979 GlobalVariable *G = GlobalsToChange[i];
980 PointerType *PtrTy = cast<PointerType>(G->getType());
981 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000982 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000983 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000984 // MinRZ <= RZ <= kMaxGlobalRedzone
985 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000986 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000987 std::min(kMaxGlobalRedzone,
988 (SizeInBytes / MinRZ / 4) * MinRZ));
989 uint64_t RightRedzoneSize = RZ;
990 // Round up to MinRZ
991 if (SizeInBytes % MinRZ)
992 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
993 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000994 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000995 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000996 bool GlobalHasDynamicInitializer =
997 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000998 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +0000999 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001000
1001 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1002 Constant *NewInitializer = ConstantStruct::get(
1003 NewTy, G->getInitializer(),
1004 Constant::getNullValue(RightRedZoneTy), NULL);
1005
Kostya Serebryany086a4722013-03-18 08:05:29 +00001006 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001007
1008 // Create a new global variable with enough space for a redzone.
Bill Wendling55a1a592013-08-06 22:52:42 +00001009 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1010 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1011 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001012 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001013 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001014 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001015 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +00001016 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001017
1018 Value *Indices2[2];
1019 Indices2[0] = IRB.getInt32(0);
1020 Indices2[1] = IRB.getInt32(0);
1021
1022 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +00001023 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001024 NewGlobal->takeName(G);
1025 G->eraseFromParent();
1026
1027 Initializers[i] = ConstantStruct::get(
1028 GlobalStructTy,
1029 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1030 ConstantInt::get(IntptrTy, SizeInBytes),
1031 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1032 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +00001033 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001034 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001035 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001036
1037 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001038 if (CheckInitOrder && GlobalHasDynamicInitializer)
1039 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001040
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001041 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001042 }
1043
1044 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1045 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001046 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001047 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1048
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001049 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001050 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1051 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001052 IRB.CreateCall2(AsanRegisterGlobals,
1053 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1054 ConstantInt::get(IntptrTy, n));
1055
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001056 // We also need to unregister globals at the end, e.g. when a shared library
1057 // gets closed.
1058 Function *AsanDtorFunction = Function::Create(
1059 FunctionType::get(Type::getVoidTy(*C), false),
1060 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1061 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1062 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001063 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1064 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1065 ConstantInt::get(IntptrTy, n));
1066 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1067
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001068 DEBUG(dbgs() << M);
1069 return true;
1070}
1071
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001072void AddressSanitizer::initializeCallbacks(Module &M) {
1073 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001074 // Create __asan_report* callbacks.
1075 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1076 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1077 AccessSizeIndex++) {
1078 // IsWrite and TypeSize are encoded in the function name.
1079 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1080 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001081 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001082 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1083 checkInterfaceFunction(M.getOrInsertFunction(
1084 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001085 }
1086 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001087 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1088 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1089 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1090 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001091
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001092 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1093 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Bob Wilson4b899142013-11-15 07:16:09 +00001094 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1095 kAsanCovName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001096 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1097 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1098 StringRef(""), StringRef(""),
1099 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001100}
1101
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001102void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001103 // Tell the values of mapping offset and scale to the run-time.
1104 GlobalValue *asan_mapping_offset =
1105 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1106 ConstantInt::get(IntptrTy, Mapping.Offset),
1107 kAsanMappingOffsetName);
1108 // Read the global, otherwise it may be optimized away.
1109 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001110
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001111 GlobalValue *asan_mapping_scale =
1112 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1113 ConstantInt::get(IntptrTy, Mapping.Scale),
1114 kAsanMappingScaleName);
1115 // Read the global, otherwise it may be optimized away.
1116 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001117}
1118
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001119// virtual
1120bool AddressSanitizer::doInitialization(Module &M) {
1121 // Initialize the private fields. No one has accessed them before.
1122 TD = getAnalysisIfAvailable<DataLayout>();
1123
1124 if (!TD)
1125 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +00001126 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001127 DynamicallyInitializedGlobals.Init(M);
1128
1129 C = &(M.getContext());
1130 LongSize = TD->getPointerSizeInBits();
1131 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001132
1133 AsanCtorFunction = Function::Create(
1134 FunctionType::get(Type::getVoidTy(*C), false),
1135 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1136 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1137 // call __asan_init in the module ctor.
1138 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1139 AsanInitFunction = checkInterfaceFunction(
1140 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1141 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1142 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001143
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001144 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001145 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001146
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001147 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001148 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001149}
1150
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001151bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1152 // For each NSObject descendant having a +load method, this method is invoked
1153 // by the ObjC runtime before any of the static constructors is called.
1154 // Therefore we need to instrument such methods with a call to __asan_init
1155 // at the beginning in order to initialize our runtime before any access to
1156 // the shadow memory.
1157 // We cannot just ignore these methods, because they may call other
1158 // instrumented functions.
1159 if (F.getName().find(" load]") != std::string::npos) {
1160 IRBuilder<> IRB(F.begin()->begin());
1161 IRB.CreateCall(AsanInitFunction);
1162 return true;
1163 }
1164 return false;
1165}
1166
Bob Wilson4b899142013-11-15 07:16:09 +00001167// Poor man's coverage that works with ASan.
1168// We create a Guard boolean variable with the same linkage
1169// as the function and inject this code into the entry block:
1170// if (*Guard) {
1171// __sanitizer_cov(&F);
1172// *Guard = 1;
1173// }
1174// The accesses to Guard are atomic. The rest of the logic is
1175// in __sanitizer_cov (it's fine to call it more than once).
1176//
1177// This coverage implementation provides very limited data:
1178// it only tells if a given function was ever executed.
1179// No counters, no per-basic-block or per-edge data.
1180// But for many use cases this is what we need and the added slowdown
1181// is negligible. This simple implementation will probably be obsoleted
1182// by the upcoming Clang-based coverage implementation.
1183// By having it here and now we hope to
1184// a) get the functionality to users earlier and
1185// b) collect usage statistics to help improve Clang coverage design.
1186bool AddressSanitizer::InjectCoverage(Function &F) {
1187 if (!ClCoverage) return false;
1188 IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt());
1189 Type *Int8Ty = IRB.getInt8Ty();
1190 GlobalVariable *Guard = new GlobalVariable(
Kostya Serebryany8f15c682013-11-15 09:52:05 +00001191 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Bob Wilson4b899142013-11-15 07:16:09 +00001192 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1193 LoadInst *Load = IRB.CreateLoad(Guard);
1194 Load->setAtomic(Monotonic);
1195 Load->setAlignment(1);
1196 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1197 Instruction *Ins = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1198 IRB.SetInsertPoint(Ins);
1199 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1200 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1201 IRB.CreateCall(AsanCovFunction, IRB.CreatePointerCast(&F, IntptrTy));
1202 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1203 Store->setAtomic(Monotonic);
1204 Store->setAlignment(1);
1205 return true;
1206}
1207
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001208bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001209 if (BL->isIn(F)) return false;
1210 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001211 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001212 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001213 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001214
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001215 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001216 maybeInsertAsanInitAtFunctionEntry(F);
1217
Kostya Serebryany20985712013-06-26 09:18:17 +00001218 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001219 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001220
1221 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1222 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001223
1224 // We want to instrument every address only once per basic block (unless there
1225 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001226 SmallSet<Value*, 16> TempsToInstrument;
1227 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001228 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001229 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001230 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001231
1232 // Fill the set of memory operations to instrument.
1233 for (Function::iterator FI = F.begin(), FE = F.end();
1234 FI != FE; ++FI) {
1235 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001236 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001237 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1238 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001239 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001240 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001241 if (ClOpt && ClOptSameTemp) {
1242 if (!TempsToInstrument.insert(Addr))
1243 continue; // We've seen this temp in the current BB.
1244 }
1245 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1246 // ok, take it.
1247 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001248 if (isa<AllocaInst>(BI))
1249 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001250 CallSite CS(BI);
1251 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001252 // A call inside BB.
1253 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001254 if (CS.doesNotReturn())
1255 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001256 }
1257 continue;
1258 }
1259 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001260 NumInsnsPerBB++;
1261 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1262 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001263 }
1264 }
1265
Kostya Serebryany20985712013-06-26 09:18:17 +00001266 Function *UninstrumentedDuplicate = 0;
1267 bool LikelyToInstrument =
1268 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1269 if (ClKeepUninstrumented && LikelyToInstrument) {
1270 ValueToValueMapTy VMap;
1271 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1272 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1273 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1274 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1275 }
1276
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001277 // Instrument.
1278 int NumInstrumented = 0;
1279 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1280 Instruction *Inst = ToInstrument[i];
1281 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1282 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001283 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001284 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001285 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001286 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001287 }
1288 NumInstrumented++;
1289 }
1290
Alexey Samsonov59cca132012-12-25 12:04:36 +00001291 FunctionStackPoisoner FSP(F, *this);
1292 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001293
1294 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1295 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1296 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1297 Instruction *CI = NoReturnCalls[i];
1298 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001299 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001300 }
1301
Kostya Serebryany20985712013-06-26 09:18:17 +00001302 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilson4b899142013-11-15 07:16:09 +00001303
1304 if (InjectCoverage(F))
1305 res = true;
1306
Kostya Serebryany20985712013-06-26 09:18:17 +00001307 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1308
1309 if (ClKeepUninstrumented) {
1310 if (!res) {
1311 // No instrumentation is done, no need for the duplicate.
1312 if (UninstrumentedDuplicate)
1313 UninstrumentedDuplicate->eraseFromParent();
1314 } else {
1315 // The function was instrumented. We must have the duplicate.
1316 assert(UninstrumentedDuplicate);
1317 UninstrumentedDuplicate->setSection("NOASAN");
1318 assert(!F.hasSection());
1319 F.setSection("ASAN");
1320 }
1321 }
1322
1323 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001324}
1325
1326static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1327 if (ShadowRedzoneSize == 1) return PoisonByte;
1328 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1329 if (ShadowRedzoneSize == 4)
1330 return (PoisonByte << 24) + (PoisonByte << 16) +
1331 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001332 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001333}
1334
1335static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1336 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001337 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001338 size_t ShadowGranularity,
1339 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001340 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001341 i+= ShadowGranularity, Shadow++) {
1342 if (i + ShadowGranularity <= Size) {
1343 *Shadow = 0; // fully addressable
1344 } else if (i >= Size) {
1345 *Shadow = Magic; // unaddressable
1346 } else {
1347 *Shadow = Size - i; // first Size-i bytes are addressable
1348 }
1349 }
1350}
1351
Alexey Samsonov59cca132012-12-25 12:04:36 +00001352// Workaround for bug 11395: we don't want to instrument stack in functions
1353// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1354// FIXME: remove once the bug 11395 is fixed.
1355bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1356 if (LongSize != 32) return false;
1357 CallInst *CI = dyn_cast<CallInst>(I);
1358 if (!CI || !CI->isInlineAsm()) return false;
1359 if (CI->getNumArgOperands() <= 5) return false;
1360 // We have inline assembly with quite a few arguments.
1361 return true;
1362}
1363
1364void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1365 IRBuilder<> IRB(*C);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001366 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1367 std::string Suffix = itostr(i);
1368 AsanStackMallocFunc[i] = checkInterfaceFunction(
1369 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1370 IntptrTy, IntptrTy, NULL));
1371 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1372 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1373 IntptrTy, IntptrTy, NULL));
1374 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001375 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1376 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1377 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1378 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1379}
1380
1381void FunctionStackPoisoner::poisonRedZones(
Jakub Staszak4c710642013-08-09 20:53:48 +00001382 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001383 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001384 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001385 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1386 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1387 Type *RZPtrTy = PointerType::get(RZTy, 0);
1388
1389 Value *PoisonLeft = ConstantInt::get(RZTy,
1390 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1391 Value *PoisonMid = ConstantInt::get(RZTy,
1392 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1393 Value *PoisonRight = ConstantInt::get(RZTy,
1394 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1395
1396 // poison the first red zone.
1397 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1398
1399 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001400 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001401 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1402 AllocaInst *AI = AllocaVec[i];
1403 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1404 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001405 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001406 Value *Ptr = NULL;
1407
1408 Pos += AlignedSize;
1409
1410 assert(ShadowBase->getType() == IntptrTy);
1411 if (SizeInBytes < AlignedSize) {
1412 // Poison the partial redzone at right
1413 Ptr = IRB.CreateAdd(
1414 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001415 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001416 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001417 uint32_t Poison = 0;
1418 if (DoPoison) {
1419 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001420 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001421 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001422 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001423 Poison =
1424 ASan.TD->isLittleEndian()
1425 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1426 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001427 }
1428 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1429 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1430 }
1431
1432 // Poison the full redzone at right.
1433 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001434 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001435 bool LastAlloca = (i == AllocaVec.size() - 1);
1436 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001437 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1438
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001439 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001440 }
1441}
1442
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001443// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1444// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1445static int StackMallocSizeClass(uint64_t LocalStackSize) {
1446 assert(LocalStackSize <= kMaxStackMallocSize);
1447 uint64_t MaxSize = kMinStackMallocSize;
1448 for (int i = 0; ; i++, MaxSize *= 2)
1449 if (LocalStackSize <= MaxSize)
1450 return i;
1451 llvm_unreachable("impossible LocalStackSize");
1452}
1453
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001454// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1455// We can not use MemSet intrinsic because it may end up calling the actual
1456// memset. Size is a multiple of 8.
1457// Currently this generates 8-byte stores on x86_64; it may be better to
1458// generate wider stores.
1459void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1460 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1461 assert(!(Size % 8));
1462 assert(kAsanStackAfterReturnMagic == 0xf5);
1463 for (int i = 0; i < Size; i += 8) {
1464 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1465 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1466 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1467 }
1468}
1469
Alexey Samsonov59cca132012-12-25 12:04:36 +00001470void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001471 uint64_t LocalStackSize = TotalStackSize +
1472 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001473
Alexey Samsonov59cca132012-12-25 12:04:36 +00001474 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001475 && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001476 int StackMallocIdx = -1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001477
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001478 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001479 Instruction *InsBefore = AllocaVec[0];
1480 IRBuilder<> IRB(InsBefore);
1481
1482
1483 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1484 AllocaInst *MyAlloca =
1485 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001486 if (ClRealignStack && StackAlignment < RedzoneSize())
1487 StackAlignment = RedzoneSize();
1488 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001489 assert(MyAlloca->isStaticAlloca());
1490 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1491 Value *LocalStackBase = OrigStackBase;
1492
1493 if (DoStackMalloc) {
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001494 // LocalStackBase = OrigStackBase
1495 // if (__asan_option_detect_stack_use_after_return)
1496 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001497 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1498 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001499 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1500 kAsanOptionDetectUAR, IRB.getInt32Ty());
1501 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1502 Constant::getNullValue(IRB.getInt32Ty()));
1503 Instruction *Term =
1504 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1505 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1506 IRBuilder<> IRBIf(Term);
1507 LocalStackBase = IRBIf.CreateCall2(
1508 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001509 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001510 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1511 IRB.SetInsertPoint(InsBefore);
1512 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1513 Phi->addIncoming(OrigStackBase, CmpBlock);
1514 Phi->addIncoming(LocalStackBase, SetBlock);
1515 LocalStackBase = Phi;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001516 }
1517
Kostya Serebryany30160562013-03-22 10:37:20 +00001518 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001519 SmallString<2048> StackDescriptionStorage;
1520 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001521 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001522
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001523 // Insert poison calls for lifetime intrinsics for alloca.
1524 bool HavePoisonedAllocas = false;
1525 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1526 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
Alexey Samsonov64409ad2013-11-18 14:53:55 +00001527 assert(APC.InsBefore);
1528 assert(APC.AI);
1529 IRBuilder<> IRB(APC.InsBefore);
1530 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001531 HavePoisonedAllocas |= APC.DoPoison;
1532 }
1533
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001534 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001535 // Replace Alloca instructions with base+offset.
1536 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1537 AllocaInst *AI = AllocaVec[i];
1538 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1539 StringRef Name = AI->getName();
1540 StackDescription << Pos << " " << SizeInBytes << " "
1541 << Name.size() << " " << Name << " ";
1542 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001543 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001544 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001545 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001546 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001547 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001548 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001549 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001550 }
1551 assert(Pos == LocalStackSize);
1552
Kostya Serebryany30160562013-03-22 10:37:20 +00001553 // The left-most redzone has enough space for at least 4 pointers.
1554 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001555 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1556 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1557 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001558 // Write the frame description constant to redzone[1].
1559 Value *BasePlus1 = IRB.CreateIntToPtr(
1560 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1561 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001562 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001563 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001564 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1565 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001566 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001567 // Write the PC to redzone[2].
1568 Value *BasePlus2 = IRB.CreateIntToPtr(
1569 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1570 2 * ASan.LongSize/8)),
1571 IntptrPtrTy);
1572 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001573
1574 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001575 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1576 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001577
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001578 // Unpoison the stack before all ret instructions.
1579 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1580 Instruction *Ret = RetVec[i];
1581 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001582 // Mark the current frame as retired.
1583 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1584 BasePlus0);
1585 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001586 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001587 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001588 assert(StackMallocIdx >= 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001589 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001590 if (StackMallocIdx <= 4) {
1591 // For small sizes inline the whole thing:
1592 // if LocalStackBase != OrigStackBase:
1593 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1594 // **SavedFlagPtr(LocalStackBase) = 0
1595 // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1596 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1597 TerminatorInst *PoisonTerm =
1598 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1599 IRBuilder<> IRBPoison(PoisonTerm);
1600 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1601 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1602 ClassSize >> Mapping.Scale);
1603 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1604 LocalStackBase,
1605 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1606 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1607 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1608 IRBPoison.CreateStore(
1609 Constant::getNullValue(IRBPoison.getInt8Ty()),
1610 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1611 } else {
1612 // For larger frames call __asan_stack_free_*.
1613 IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1614 ConstantInt::get(IntptrTy, LocalStackSize),
1615 OrigStackBase);
1616 }
Alexey Samsonovf985f442012-12-04 01:34:23 +00001617 } else if (HavePoisonedAllocas) {
1618 // If we poisoned some allocas in llvm.lifetime analysis,
1619 // unpoison whole stack frame now.
1620 assert(LocalStackBase == OrigStackBase);
1621 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001622 }
1623 }
1624
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001625 // We are done. Remove the old unused alloca instructions.
1626 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1627 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001628}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001629
Alexey Samsonov59cca132012-12-25 12:04:36 +00001630void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak4c710642013-08-09 20:53:48 +00001631 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001632 // For now just insert the call to ASan runtime.
1633 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1634 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1635 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1636 : AsanUnpoisonStackMemoryFunc,
1637 AddrArg, SizeArg);
1638}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001639
1640// Handling llvm.lifetime intrinsics for a given %alloca:
1641// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1642// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1643// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1644// could be poisoned by previous llvm.lifetime.end instruction, as the
1645// variable may go in and out of scope several times, e.g. in loops).
1646// (3) if we poisoned at least one %alloca in a function,
1647// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001648
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001649AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1650 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1651 // We're intested only in allocas we can handle.
1652 return isInterestingAlloca(*AI) ? AI : 0;
1653 // See if we've already calculated (or started to calculate) alloca for a
1654 // given value.
1655 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1656 if (I != AllocaForValue.end())
1657 return I->second;
1658 // Store 0 while we're calculating alloca for value V to avoid
1659 // infinite recursion if the value references itself.
1660 AllocaForValue[V] = 0;
1661 AllocaInst *Res = 0;
1662 if (CastInst *CI = dyn_cast<CastInst>(V))
1663 Res = findAllocaForValue(CI->getOperand(0));
1664 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1665 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1666 Value *IncValue = PN->getIncomingValue(i);
1667 // Allow self-referencing phi-nodes.
1668 if (IncValue == PN) continue;
1669 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1670 // AI for incoming values should exist and should all be equal.
1671 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1672 return 0;
1673 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001674 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001675 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001676 if (Res != 0)
1677 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001678 return Res;
1679}